Skip to content

Commit

Permalink
Merge pull request #226 from joshnuss/optional-sync
Browse files Browse the repository at this point in the history
Adds option to disable syncing across tabs
  • Loading branch information
joshnuss authored Dec 20, 2023
2 parents 62ddd27 + f92bec9 commit ac50568
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 3 deletions.
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
})
```

Expand Down
6 changes: 4 additions & 2 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@ export type StorageType = 'local' | 'session'

export interface Options<T> {
serializer?: Serializer<T>
storage?: StorageType
storage?: StorageType,
syncTabs: boolean
}

function getStorage(type: StorageType) {
Expand All @@ -38,6 +39,7 @@ export function writable<T>(key: string, initialValue: T, options?: Options<T>):
export function persisted<T>(key: string, initialValue: T, options?: Options<T>): Writable<T> {
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

Expand All @@ -53,7 +55,7 @@ export function persisted<T>(key: string, initialValue: T, options?: Options<T>)
set(<T>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)
Expand Down
16 changes: 16 additions & 0 deletions test/localStorageStore.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down

0 comments on commit ac50568

Please sign in to comment.