Merge pull request #1944 from adesurirey/pr/reset-useLocalStorage-state-on-key-change

fix(useLocalStorage): reinitialize on key change
This commit is contained in:
Anton Zinovyev 2021-04-23 10:15:17 +03:00 committed by GitHub
commit 5fd995eaf8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 21 additions and 2 deletions

View File

@ -1,4 +1,4 @@
import { Dispatch, SetStateAction, useCallback, useState } from 'react';
import { Dispatch, SetStateAction, useCallback, useState, useRef, useLayoutEffect } from 'react';
import { isBrowser, noop } from './misc/util';
type parserOptions<T> =
@ -30,7 +30,7 @@ const useLocalStorage = <T>(
: JSON.parse;
// eslint-disable-next-line react-hooks/rules-of-hooks
const [state, setState] = useState<T | undefined>(() => {
const initializer = useRef((key: string) => {
try {
const serializer = options ? (options.raw ? String : options.serializer) : JSON.stringify;
@ -49,6 +49,12 @@ const useLocalStorage = <T>(
}
});
// eslint-disable-next-line react-hooks/rules-of-hooks
const [state, setState] = useState<T | undefined>(() => initializer.current(key));
// eslint-disable-next-line react-hooks/rules-of-hooks
useLayoutEffect(() => setState(initializer.current(key)), [key]);
// eslint-disable-next-line react-hooks/rules-of-hooks
const set: Dispatch<SetStateAction<T | undefined>> = useCallback(
(valOrFunc) => {

View File

@ -80,6 +80,19 @@ describe(useLocalStorage, () => {
expect(foo).toEqual('baz');
});
it('reinitializes state when key changes', () => {
let key = 'foo';
const { result, rerender } = renderHook(() => useLocalStorage(key, 'bar'));
const [, setState] = result.current;
act(() => setState('baz'));
key = 'bar';
rerender();
const [state] = result.current;
expect(state).toEqual('bar');
});
/*
it('keeps multiple hooks accessing the same key in sync', () => {
localStorage.setItem('foo', 'bar');