( key: string, defaultValue: T | undefined, )
| 14 | } |
| 15 | |
| 16 | export default function useLocalStorage<T>( |
| 17 | key: string, |
| 18 | defaultValue: T | undefined, |
| 19 | ): [Accessor<T | undefined>, (newVal: T | ((prevVal: T) => T)) => void] { |
| 20 | const [value, setValue] = createSignal<T>() |
| 21 | |
| 22 | onSettled(() => { |
| 23 | const initialValue = getItem(key) as T | undefined |
| 24 | |
| 25 | if (typeof initialValue === 'undefined' || initialValue === null) { |
| 26 | setValue( |
| 27 | typeof defaultValue === 'function' ? defaultValue() : defaultValue, |
| 28 | ) |
| 29 | } else { |
| 30 | // eslint-disable-next-line @typescript-eslint/ban-ts-comment |
| 31 | // @ts-ignore |
| 32 | setValue(initialValue) |
| 33 | } |
| 34 | }) |
| 35 | |
| 36 | const setter = (updater: any) => { |
| 37 | setValue((old) => { |
| 38 | let newVal = updater |
| 39 | |
| 40 | if (typeof updater == 'function') { |
| 41 | newVal = updater(old) |
| 42 | } |
| 43 | try { |
| 44 | localStorage.setItem(key, JSON.stringify(newVal)) |
| 45 | } catch {} |
| 46 | |
| 47 | return newVal |
| 48 | }) |
| 49 | } |
| 50 | |
| 51 | return [value, setter] |
| 52 | } |
no test coverage detected