File size: 2,002 Bytes
f0743f4 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 | /* `useLocalStorage`
*
* Features:
* - JSON Serializing
* - Also value will be updated everywhere, when value updated (via `storage` event)
*/
import { useEffect, useState, useCallback } from 'react';
export default function useLocalStorage<T>(
key: string,
defaultValue: T,
globalSetState?: (value: T) => void,
storageCondition?: (value: T, rawCurrentValue?: string | null) => boolean,
): [T, (value: T) => void] {
const [value, setValue] = useState(defaultValue);
useEffect(() => {
const item = localStorage.getItem(key);
if (!item && !storageCondition) {
localStorage.setItem(key, JSON.stringify(defaultValue));
} else if (!item && storageCondition && storageCondition(defaultValue)) {
localStorage.setItem(key, JSON.stringify(defaultValue));
}
const initialValue = item && item !== 'undefined' ? JSON.parse(item) : defaultValue;
setValue(initialValue);
if (globalSetState) {
globalSetState(initialValue);
}
function handler(e: StorageEvent) {
if (e.key !== key) {
return;
}
const lsi = localStorage.getItem(key);
setValue(JSON.parse(lsi ?? ''));
}
window.addEventListener('storage', handler);
return () => {
window.removeEventListener('storage', handler);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [key, globalSetState]);
const setValueWrap = useCallback(
(value: T) => {
try {
setValue(value);
const storeLocal = () => {
localStorage.setItem(key, JSON.stringify(value));
window?.dispatchEvent(new StorageEvent('storage', { key }));
};
if (!storageCondition) {
storeLocal();
} else if (storageCondition(value, localStorage.getItem(key))) {
storeLocal();
}
globalSetState?.(value);
} catch (e) {
console.error(e);
}
},
[key, globalSetState, storageCondition],
);
return [value, setValueWrap];
}
|