Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 65a99c4

Browse files
authored
fix: always mount listeners in useStorage (#4730)
1 parent 9889fa0 commit 65a99c4

File tree

1 file changed

+33
-18
lines changed

1 file changed

+33
-18
lines changed

packages/core/useStorage/index.ts

+33-18
Original file line numberDiff line numberDiff line change
@@ -181,29 +181,44 @@ export function useStorage<T extends (string | number | boolean | object | null)
181181

182182
watch(keyComputed, () => update(), { flush })
183183

184+
let firstMounted = false
185+
const onStorageEvent = (ev: StorageEvent): void => {
186+
if (initOnMounted && !firstMounted) {
187+
return
188+
}
189+
190+
update(ev)
191+
}
192+
const onStorageCustomEvent = (ev: CustomEvent<StorageEventLike>): void => {
193+
if (initOnMounted && !firstMounted) {
194+
return
195+
}
196+
197+
updateFromCustomEvent(ev)
198+
}
199+
200+
/**
201+
* The custom event is needed for same-document syncing when using custom
202+
* storage backends, but it doesn't work across different documents.
203+
*
204+
* TODO: Consider implementing a BroadcastChannel-based solution that fixes this.
205+
*/
184206
if (window && listenToStorageChanges) {
185-
tryOnMounted(() => {
186-
/**
187-
* Attaching event listeners here should be fine since we are in a mounted hook
188-
*
189-
* The custom event is needed for same-document syncing when using custom
190-
* storage backends, but it doesn't work across different documents.
191-
*
192-
* TODO: Consider implementing a BroadcastChannel-based solution that fixes this.
193-
*/
194-
if (storage instanceof Storage)
195-
useEventListener(window, 'storage', update, { passive: true })
196-
else
197-
useEventListener(window, customStorageEventName, updateFromCustomEvent)
207+
if (storage instanceof Storage)
208+
useEventListener(window, 'storage', onStorageEvent, { passive: true })
209+
else
210+
useEventListener(window, customStorageEventName, onStorageCustomEvent)
211+
}
198212

199-
if (initOnMounted)
200-
update()
213+
if (initOnMounted) {
214+
tryOnMounted(() => {
215+
firstMounted = true
216+
update()
201217
})
202218
}
203-
204-
// avoid reading immediately to avoid hydration mismatch when doing SSR
205-
if (!initOnMounted)
219+
else {
206220
update()
221+
}
207222

208223
function dispatchWriteEvent(oldValue: string | null, newValue: string | null) {
209224
// send custom event to communicate within same page

0 commit comments

Comments
 (0)