Skip to content

Commit

Permalink
🐛 removeItem() doesn't batch updates
Browse files Browse the repository at this point in the history
  • Loading branch information
astoilkov committed Mar 27, 2022
1 parent be1cd55 commit 6b0e95b
Showing 1 changed file with 12 additions and 13 deletions.
25 changes: 12 additions & 13 deletions src/useLocalStorageState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,15 @@ function useClientLocalStorageState<T>(
const defaultValue = useRef(options?.defaultValue).current
// `id` changes every time a change in the `localStorage` occurs
const [id, forceUpdate] = useReducer((number) => number + 1, 0)
const updateHooks = useCallback(() => {
unstable_batchedUpdates(() => {
for (const hook of activeHooks) {
if (hook.key === key) {
hook.forceUpdate()
}
}
})
}, [key])
const setState = useCallback(
(newValue: SetStateAction<T | undefined>): void => {
const isCallable = (value: unknown): value is (value: T | undefined) => T | undefined =>
Expand All @@ -67,15 +76,9 @@ function useClientLocalStorageState<T>(

storage.set(key, newUnwrappedValue)

unstable_batchedUpdates(() => {
for (const hook of activeHooks) {
if (hook.key === key) {
hook.forceUpdate()
}
}
})
updateHooks()
},
[key, defaultValue],
[key, updateHooks, defaultValue],
)

// - syncs change across tabs, windows, iframe's
Expand Down Expand Up @@ -144,11 +147,7 @@ function useClientLocalStorageState<T>(
removeItem(): void {
storage.remove(key)

for (const update of activeHooks) {
if (update.key === key) {
update.forceUpdate()
}
}
updateHooks()
},
},
],
Expand Down

0 comments on commit 6b0e95b

Please sign in to comment.