| 2 | import {logger} from '#preact/logger'; |
| 3 | |
| 4 | export function useLocalStorage<T>( |
| 5 | key: string, |
| 6 | defaultValue: T |
| 7 | ): readonly [T, (newValue: T) => void] { |
| 8 | // Keep track of the state locally: |
| 9 | const [value, setValue] = useState(() => { |
| 10 | try { |
| 11 | const json = self.localStorage?.getItem(key); |
| 12 | return json ? JSON.parse(json) : defaultValue; |
| 13 | } catch (err) { |
| 14 | // warning: could not read from local storage |
| 15 | return defaultValue; |
| 16 | } |
| 17 | }); |
| 18 | |
| 19 | const storeValue = useCallback( |
| 20 | (newValue: T) => { |
| 21 | try { |
| 22 | const json = JSON.stringify(newValue); |
| 23 | self.localStorage?.setItem(key, json); |
| 24 | } catch (err) { |
| 25 | logger.warn( |
| 26 | 'useLocalStorage', |
| 27 | 'Could not write value to local storage', |
| 28 | key, |
| 29 | err |
| 30 | ); |
| 31 | } |
| 32 | setValue(newValue); |
| 33 | }, |
| 34 | [key] |
| 35 | ); |
| 36 | |
| 37 | return [value, storeValue] as const; |
| 38 | } |