( key: string, defaultValue: T, )
| 12 | import storageAvailable from "~/utils/storageAvailable"; |
| 13 | |
| 14 | function useLocalStorage<T>( |
| 15 | key: string, |
| 16 | defaultValue: T, |
| 17 | ): [T, Dispatch<SetStateAction<T>>] { |
| 18 | const [value, setValue] = useState(() => { |
| 19 | let currentValue = defaultValue; |
| 20 | |
| 21 | if (storageAvailable("localStorage")) { |
| 22 | const localStorageValue = localStorage.getItem(key); |
| 23 | if (localStorageValue !== null) { |
| 24 | currentValue = JSON.parse(localStorageValue) as T; |
| 25 | } |
| 26 | } |
| 27 | |
| 28 | return currentValue; |
| 29 | }); |
| 30 | |
| 31 | useEffect(() => { |
| 32 | if (storageAvailable("localStorage")) { |
| 33 | localStorage.setItem(key, JSON.stringify(value)); |
| 34 | } |
| 35 | }, [value, key]); |
| 36 | |
| 37 | return [value, setValue]; |
| 38 | } |
| 39 | |
| 40 | export default useLocalStorage; |
no test coverage detected