diff --git a/index.ts b/index.ts index 81a0239..cf2b21d 100644 --- a/index.ts +++ b/index.ts @@ -53,14 +53,19 @@ export function persisted(key: string, initialValue: T, options?: Options) } } - if (!stores[storageType][key]) { - const store = internal(initialValue, (set) => { - const json = storage?.getItem(key) + function maybeLoadInitial(): T { + const json = storage?.getItem(key) - if (json) { - set(serializer.parse(json)) - } + if (json) { + return serializer.parse(json) + } + return initialValue + } + + if (!stores[storageType][key]) { + const initial = maybeLoadInitial() + const store = internal(initial, (set) => { if (browser && storageType == 'local' && syncTabs) { const handleStorage = (event: StorageEvent) => { if (event.key === key) diff --git a/test/localStorageStore.test.ts b/test/localStorageStore.test.ts index 986a2b9..557e7f3 100644 --- a/test/localStorageStore.test.ts +++ b/test/localStorageStore.test.ts @@ -76,6 +76,14 @@ describe('persisted()', () => { expect(localStorage.myKey6).toEqual('124') expect(value).toEqual(124) }) + + test("BUG: update should use existing value", () => { + localStorage.setItem('myKey6b', '12345') + const store = persisted('myKey6b', 123) + store.update(n => { n += 1; return n }) + + expect(localStorage.myKey6b).toEqual('12346') + }) }) describe('subscribe()', () => { @@ -176,12 +184,13 @@ describe('persisted()', () => { }) it("doesn't update store when there are no subscribers", () => { - const store = persisted('myKey', 1) + localStorage.setItem('myKeyb', '2') + + const store = persisted('myKeyb', 1) const values: number[] = [] - const event = new StorageEvent('storage', {key: 'myKey', newValue: '2'}) + const event = new StorageEvent('storage', {key: 'myKeyb', newValue: '2'}) window.dispatchEvent(event) - localStorage.setItem('myKey', '2') const unsub = store.subscribe((value: number) => { values.push(value)