Skip to content

Commit

Permalink
fix(451): attempt to fix issue #451 (#539)
Browse files Browse the repository at this point in the history
fix: #451
  • Loading branch information
xobotyi authored Dec 23, 2021
1 parent 8c97138 commit c2f99da
Showing 1 changed file with 13 additions and 8 deletions.
21 changes: 13 additions & 8 deletions src/useStorageValue/useStorageValue.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -114,7 +115,11 @@ export function useStorageValue<T>(
options: IUseStorageValueOptions = {}
): IHookReturn<T, typeof defaultValue, typeof options> {
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) {
Expand Down Expand Up @@ -176,19 +181,16 @@ export function useStorageValue<T>(
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
useUpdateEffect(() => {
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) => {
Expand All @@ -207,7 +209,8 @@ export function useStorageValue<T>(
// 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);
Expand Down Expand Up @@ -246,6 +249,7 @@ export function useStorageValue<T>(
methods.current.setState(s);

if (!isolatedRef.current) {
// update all other hooks state
storageKeysUsed
.get(storage)
?.get(keyRef.current)
Expand Down Expand Up @@ -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;

Expand Down

0 comments on commit c2f99da

Please sign in to comment.