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(useStorage): ensure setting value to null syncs to other instances #3737

Merged
merged 4 commits into from
Feb 20, 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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
15 changes: 15 additions & 0 deletions packages/core/useStorage/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -464,6 +464,21 @@ describe('useStorage', () => {
expect(call[0].detail.key).toEqual(KEY)
expect(call[0].detail.oldValue).toEqual('0')
expect(call[0].detail.newValue).toEqual('1')

window.addEventListener(customStorageEventName, eventFn, { once: true })

data0.value = null
await nextTwoTick()

expect(data0.value).toBe(0)
expect(data1.value).toBe(0)
expect(eventFn).toHaveBeenCalledTimes(2)
const call2 = eventFn.mock.calls[1] as [CustomEvent]

expect(call2[0].detail.storageArea).toEqual(storage)
expect(call2[0].detail.key).toEqual(KEY)
expect(call2[0].detail.oldValue).toEqual('1')
expect(call2[0].detail.newValue).toEqual(null)
})

it('handle error', () => {
Expand Down
35 changes: 20 additions & 15 deletions packages/core/useStorage/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -195,28 +195,33 @@ export function useStorage<T extends(string | number | boolean | object | null)>

function write(v: unknown) {
try {
const oldValue = storage!.getItem(key)

const dispatchWriteEvent = (newValue: string | null) => {
// send custom event to communicate within same page
// importantly this should _not_ be a StorageEvent since those cannot
// be constructed with a non-built-in storage area
if (window) {
window.dispatchEvent(new CustomEvent<StorageEventLike>(customStorageEventName, {
detail: {
key,
oldValue,
newValue,
storageArea: storage!,
},
}))
}
}

if (v == null) {
dispatchWriteEvent(null)
storage!.removeItem(key)
}
else {
const serialized = serializer.write(v as any)
const oldValue = storage!.getItem(key)
if (oldValue !== serialized) {
storage!.setItem(key, serialized)

// send custom event to communicate within same page
// importantly this should _not_ be a StorageEvent since those cannot
// be constructed with a non-built-in storage area
if (window) {
window.dispatchEvent(new CustomEvent<StorageEventLike>(customStorageEventName, {
detail: {
key,
oldValue,
newValue: serialized,
storageArea: storage!,
},
}))
}
dispatchWriteEvent(serialized)
}
}
}
Expand Down