Skip to content

Commit

Permalink
Merge pull request #232 from joshnuss/update-before-read
Browse files Browse the repository at this point in the history
Fix: Load initial value from storage
  • Loading branch information
joshnuss authored Jan 4, 2024
2 parents 3d3319d + 91760bd commit cc0a3d1
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 9 deletions.
17 changes: 11 additions & 6 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,14 +53,19 @@ export function persisted<T>(key: string, initialValue: T, options?: Options<T>)
}
}

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(<T>serializer.parse(json))
}
if (json) {
return <T>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)
Expand Down
15 changes: 12 additions & 3 deletions test/localStorageStore.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()', () => {
Expand Down Expand Up @@ -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)
Expand Down

0 comments on commit cc0a3d1

Please sign in to comment.