Files
cinny/src/app/state/utils/atomWithLocalStorage.ts
T
Lotus Bot 61a1f008d0 chore: upgrade i18next 26, prettier 3, fontsource-variable, domhandler 6, lint-staged 17
- i18next 23->26 + react-i18next 15->17
- prettier 2->3, reformat all files
- replace @fontsource/inter with @fontsource-variable/inter 5, update import path
- domhandler 5->6 (aligns with transitive deps)
- lint-staged 16->17
2026-05-21 23:30:50 -04:00

52 lines
1.3 KiB
TypeScript

import { atom } from 'jotai';
export const getLocalStorageItem = <T>(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 = <T>(key: string, value: T) => {
localStorage.setItem(key, JSON.stringify(value));
};
export type GetLocalStorageItem<T> = (key: string) => T;
export type SetLocalStorageItem<T> = (key: string, value: T) => void;
export const atomWithLocalStorage = <T>(
key: string,
getItem: GetLocalStorageItem<T>,
setItem: SetLocalStorageItem<T>,
) => {
const value = getItem(key);
const baseAtom = atom<T>(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<T, [T], undefined>(
(get) => get(baseAtom),
(get, set, newValue) => {
set(baseAtom, newValue);
setItem(key, newValue);
},
);
return localStorageAtom;
};