({
key,
initialValue,
parseFunction,
}: {
key: string;
initialValue: T;
parseFunction?: (value: string) => T;
})
| 1 | import { atom } from 'jotai/vanilla'; |
| 2 | |
| 3 | export const atomWithLocalStorage = <T>({ |
| 4 | key, |
| 5 | initialValue, |
| 6 | parseFunction, |
| 7 | }: { |
| 8 | key: string; |
| 9 | initialValue: T; |
| 10 | parseFunction?: (value: string) => T; |
| 11 | }) => { |
| 12 | const getInitialValue = () => { |
| 13 | const item = globalThis?.localStorage?.getItem?.(key) ?? null; |
| 14 | if (item !== null) { |
| 15 | const value = JSON.parse(item); |
| 16 | return parseFunction?.(value) ?? (value as T); |
| 17 | } |
| 18 | return initialValue; |
| 19 | }; |
| 20 | const baseAtom = atom<T>(getInitialValue()); |
| 21 | return atom( |
| 22 | (get) => get(baseAtom), |
| 23 | (get, set, update) => { |
| 24 | const nextValue = |
| 25 | typeof update === 'function' ? update(get(baseAtom)) : update; |
| 26 | set(baseAtom, nextValue); |
| 27 | localStorage?.setItem?.(key, JSON.stringify(nextValue)); |
| 28 | }, |
| 29 | ); |
| 30 | }; |
no test coverage detected