import { atom } from 'jotai'; export const getLocalStorageItem = (key: string, defaultValue: T): T => { const item = localStorage.getItem(key); if (item === null) return defaultValue; if (item === 'undefined') return undefined as T; try { return JSON.parse(item) as T; } catch { return defaultValue; } }; export const setLocalStorageItem = (key: string, value: T) => { localStorage.setItem(key, JSON.stringify(value)); }; export type GetLocalStorageItem = (key: string) => T; export type SetLocalStorageItem = (key: string, value: T) => void; export const atomWithLocalStorage = ( key: string, getItem: GetLocalStorageItem, setItem: SetLocalStorageItem ) => { const value = getItem(key); const baseAtom = atom(value); baseAtom.onMount = (setAtom) => { const handleChange = (evt: StorageEvent) => { if (evt.key !== key) return; setAtom(getItem(key)); }; window.addEventListener('storage', handleChange); return () => { window.removeEventListener('storage', handleChange); }; }; const localStorageAtom = atom( (get) => get(baseAtom), (get, set, newValue) => { set(baseAtom, newValue); setItem(key, newValue); } ); return localStorageAtom; };