Skip to content

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

@paulaeschlimann

Description

@paulaeschlimann

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions