Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix: Load initial value from storage #232

Merged
merged 2 commits into from
Jan 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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