diff --git a/index.ts b/index.ts index 683b16f..4501944 100644 --- a/index.ts +++ b/index.ts @@ -4,7 +4,15 @@ declare type Updater = (value: T) => T; declare type StoreDict = { [key: string]: Writable } /* eslint-disable @typescript-eslint/no-explicit-any */ -const stores: StoreDict = {} +interface Stores { + local: StoreDict, + session: StoreDict, +} + +const stores : Stores = { + local: {}, + session: {} +} interface Serializer { parse(text: string): T @@ -37,7 +45,7 @@ export function persisted(key: string, initialValue: T, options?: Options) storage?.setItem(key, serializer.stringify(value)) } - if (!stores[key]) { + if (!stores[storageType][key]) { const store = internal(initialValue, (set) => { const json = storage?.getItem(key) @@ -45,7 +53,7 @@ export function persisted(key: string, initialValue: T, options?: Options) set(serializer.parse(json)) } - if (browser) { + if (browser && storageType == 'local') { const handleStorage = (event: StorageEvent) => { if (event.key === key) set(event.newValue ? serializer.parse(event.newValue) : null) @@ -59,7 +67,7 @@ export function persisted(key: string, initialValue: T, options?: Options) const {subscribe, set} = store - stores[key] = { + stores[storageType][key] = { set(value: T) { updateStorage(key, value) set(value) @@ -77,5 +85,5 @@ export function persisted(key: string, initialValue: T, options?: Options) } } - return stores[key] + return stores[storageType][key] } diff --git a/test/localStorageStore.test.ts b/test/localStorageStore.test.ts index c6f6e7d..4bf4f3f 100644 --- a/test/localStorageStore.test.ts +++ b/test/localStorageStore.test.ts @@ -190,6 +190,22 @@ describe('persisted()', () => { unsub() }) + + it('ignores session-backed stores', () => { + const store = persisted('myKey10', 1, { storage: 'session' }) + const values = [] + + const unsub = store.subscribe((value) => { + values.push(value) + }) + + const event = new StorageEvent('storage', {key: 'myKey10', newValue: '2'}) + window.dispatchEvent(event) + + expect(values).toEqual([1]) + + unsub() + }) }) it('allows custom serialize/deserialize functions', () => { @@ -210,17 +226,17 @@ describe('persisted()', () => { }) it('lets you switch storage type', () => { - vi.spyOn(Object.getPrototypeOf(window.sessionStorage), 'setItem') - Object.setPrototypeOf(window.sessionStorage.setItem, vi.fn()) + vi.spyOn(Object.getPrototypeOf(window.sessionStorage), 'setItem') + Object.setPrototypeOf(window.sessionStorage.setItem, vi.fn()) - const value = 'foo' + const value = 'foo' - const store = persisted('myKey12', value, { - storage: 'session' - }) + const store = persisted('myKey12', value, { + storage: 'session' + }) - store.set('bar') + store.set('bar') - expect(window.sessionStorage.setItem).toHaveBeenCalled() + expect(window.sessionStorage.setItem).toHaveBeenCalled() }) })