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(451): attempt to fix issue #451 #539

Merged
merged 1 commit into from
Dec 23, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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