Lit component shows initial value instead of current persisted value in localStorage after page reload
Author: paulaeschlimannCreated Jul 1, 2024Updated Jul 1, 2024
I use nanostores to store a count in localStorage:
import { persistentAtom } from '@nanostores/persistent'
export const counterStore = persistentAtom('count', 0, {
encode: JSON.stringify,
decode: JSON.parse,
})Incrementing the count works as expected, the count value is updated in localStorage. However, after a page reload, the Lit component always shows the initial value 0. After clicking the increment button, the value in localStorage is read, incremented and then displayed in the Lit component.
import { LitElement, html } from 'lit';
import { StoreController } from '@nanostores/lit'
import { counterStore } from '../stores/count.js'
export class LitCounter extends LitElement {
static properties = {
count: {state: true}
};
constructor() {
super()
this.count = new StoreController(this, counterStore)
}
_increment(e) {
counterStore.set(this.count.value + 1)
}
_current(e) {
const current = this.count.value
console.log(`current: ${current}`)
}
render() {
return html`
<div>
<div>
Count ${this.count.value} (Lit)
</div>
<button @click="${this._increment}">
+ 1
</button>
<button @click="${this._current}">
Current
</button>
</div>
`;
}
}
customElements.define('lit-counter', LitCounter);Source: nanostores/nanostores