mirror of
https://github.com/streamich/react-use.git
synced 2026-01-18 14:06:52 +00:00
Merge pull request #1944 from adesurirey/pr/reset-useLocalStorage-state-on-key-change
fix(useLocalStorage): reinitialize on key change
This commit is contained in:
commit
5fd995eaf8
@ -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) => {
|
||||
|
||||
@ -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');
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user