mirror of
https://github.com/streamich/react-use.git
synced 2026-01-18 14:06:52 +00:00
There is some "Illegal invocation" that I cannot immediately solve, so postponing this hook for now.
36 lines
698 B
TypeScript
36 lines
698 B
TypeScript
import {useState, useEffect} from './react';
|
|
import {on, off} from './util';
|
|
|
|
const isClient = typeof window === 'object';
|
|
|
|
const useLocalStorage = (key: string): string | undefined => {
|
|
if (!isClient) {
|
|
return undefined;
|
|
}
|
|
|
|
const [state, setState] = useState<string | undefined>(undefined);
|
|
|
|
useEffect(() => {
|
|
try {
|
|
setState(localStorage[key]);
|
|
} catch {}
|
|
|
|
const onChange = (event) => {
|
|
console.log('onChange')
|
|
if (event.key === key) {
|
|
setState(event.newValue);
|
|
}
|
|
}
|
|
|
|
on(window, 'storage', onChange);
|
|
|
|
return () => {
|
|
off(window, 'storage', onChange);
|
|
};
|
|
}, [key]);
|
|
|
|
return state;
|
|
};
|
|
|
|
export default useLocalStorage;
|