diff --git a/README.md b/README.md index bdcccd8..76585da 100644 --- a/README.md +++ b/README.md @@ -47,7 +47,8 @@ import * as devalue from 'devalue' // third parameter is options. export const preferences = persisted('local-storage-key', 'default-value', { serializer: devalue, // defaults to `JSON` - storage: 'session' // 'session' for sessionStorage, defaults to 'local' + storage: 'session', // 'session' for sessionStorage, defaults to 'local' + syncTabs: true // choose wether to sync localStorage across tabs, default is true }) ``` diff --git a/index.ts b/index.ts index ff8dfdb..6023e01 100644 --- a/index.ts +++ b/index.ts @@ -23,7 +23,8 @@ export type StorageType = 'local' | 'session' export interface Options { serializer?: Serializer - storage?: StorageType + storage?: StorageType, + syncTabs: boolean } function getStorage(type: StorageType) { @@ -38,6 +39,7 @@ export function writable(key: string, initialValue: T, options?: Options): export function persisted(key: string, initialValue: T, options?: Options): Writable { const serializer = options?.serializer ?? JSON const storageType = options?.storage ?? 'local' + const syncTabs = options?.syncTabs ?? true const browser = typeof(window) !== 'undefined' && typeof(document) !== 'undefined' const storage = browser ? getStorage(storageType) : null @@ -53,7 +55,7 @@ export function persisted(key: string, initialValue: T, options?: Options) set(serializer.parse(json)) } - if (browser && storageType == 'local') { + if (browser && storageType == 'local' && syncTabs) { const handleStorage = (event: StorageEvent) => { if (event.key === key) set(event.newValue ? serializer.parse(event.newValue) : null) diff --git a/test/localStorageStore.test.ts b/test/localStorageStore.test.ts index 4bf4f3f..9916b49 100644 --- a/test/localStorageStore.test.ts +++ b/test/localStorageStore.test.ts @@ -206,6 +206,22 @@ describe('persisted()', () => { unsub() }) + + it("doesn't update, when syncTabs option is disabled", () => { + const store = persisted('myKey13', 1, { syncTabs: false }) + const values = [] + + const unsub = store.subscribe((value) => { + values.push(value) + }) + + const event = new StorageEvent('storage', {key: 'myKey13', newValue: '2'}) + window.dispatchEvent(event) + + expect(values).toEqual([1]) + + unsub() + }) }) it('allows custom serialize/deserialize functions', () => {