From c2f99da82b88d78488c84ad793d3e4c99b4c2141 Mon Sep 17 00:00:00 2001 From: Anton Zinovyev Date: Thu, 23 Dec 2021 14:44:39 +0300 Subject: [PATCH] fix(451): attempt to fix issue #451 (#539) fix: #451 --- src/useStorageValue/useStorageValue.ts | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/src/useStorageValue/useStorageValue.ts b/src/useStorageValue/useStorageValue.ts index 5c130a43..16207440 100644 --- a/src/useStorageValue/useStorageValue.ts +++ b/src/useStorageValue/useStorageValue.ts @@ -1,8 +1,9 @@ /* eslint-disable @typescript-eslint/no-use-before-define */ -import { useCallback, useEffect } from 'react'; +import { useCallback } from 'react'; import { useConditionalEffect, useFirstMountState, + useIsomorphicLayoutEffect, useMountEffect, usePrevious, useSafeState, @@ -114,7 +115,11 @@ export function useStorageValue( options: IUseStorageValueOptions = {} ): IHookReturn { const { isolated } = options; - let { initializeWithStorageValue = true, handleStorageEvent = true, storeDefaultValue } = options; + let { + initializeWithStorageValue = true, + handleStorageEvent = true, + storeDefaultValue = false, + } = options; // avoid fetching data from storage during SSR if (!isBrowser) { @@ -176,7 +181,7 @@ export function useStorageValue( methods.current.storeVal(defaultValue as T); }, undefined, - [prevState !== state, state === defaultValue && defaultValue !== null && storeDefaultValue] + [prevState !== state, storeDefaultValue && state === defaultValue && defaultValue !== null] ); // refetch value when key changed @@ -184,11 +189,8 @@ export function useStorageValue( methods.current.fetchState(); }, [key]); - // register hook for same-page synchronisation - useEffect(() => {}, [key]); - // subscribe hook for storage events - useEffect(() => { + useIsomorphicLayoutEffect(() => { if (!handleStorageEvent) return; const storageHandler = (ev: StorageEvent) => { @@ -207,7 +209,8 @@ export function useStorageValue( // eslint-disable-next-line react-hooks/exhaustive-deps }, [handleStorageEvent]); - useEffect(() => { + // register hook for same-page synchronisation + useIsomorphicLayoutEffect(() => { if (isolated) return; let storageKeys = storageKeysUsed.get(storage); @@ -246,6 +249,7 @@ export function useStorageValue( methods.current.setState(s); if (!isolatedRef.current) { + // update all other hooks state storageKeysUsed .get(storage) ?.get(keyRef.current) @@ -321,6 +325,7 @@ const stringify = (data: unknown): string | null => { return null; } }; + const parse = (str: string | null, fallback: unknown): unknown => { if (str === null) return fallback;