From d77aeaad4c82282c7bf84f656ec05e2dffacf545 Mon Sep 17 00:00:00 2001 From: Josh Nussbaum Date: Thu, 4 Jan 2024 15:39:35 -0500 Subject: [PATCH 1/2] fix: Load initial value from storage, when possible. Closes #231 --- index.ts | 17 +++++++++++------ test/localStorageStore.test.ts | 8 ++++++++ 2 files changed, 19 insertions(+), 6 deletions(-) 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..966bbcd 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()', () => { From 91760bd13ab5fc795aa3e3162b237e132fe7e61b Mon Sep 17 00:00:00 2001 From: Josh Nussbaum Date: Thu, 4 Jan 2024 15:52:33 -0500 Subject: [PATCH 2/2] Fix test where key was clashing with other test --- test/localStorageStore.test.ts | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/test/localStorageStore.test.ts b/test/localStorageStore.test.ts index 966bbcd..557e7f3 100644 --- a/test/localStorageStore.test.ts +++ b/test/localStorageStore.test.ts @@ -184,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)