Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Lit component does not show value stored in localStorage after page reload #14

Open
paulaeschlimann opened this issue Jul 2, 2024 · 0 comments

Comments

@paulaeschlimann
Copy link

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,
})

Updating the count value in localStorage works as expected. However, after a page reload, the Lit component does not show the value stored in localStorage, but 0 instead. 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);

I tried to integrate nanostores with StoreController and withStores, but both don't display the value stored in localStorage.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant