File size: 909 Bytes
f0743f4 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | import { atom } from 'recoil';
// Improved helper function to create atoms with localStorage
export function atomWithLocalStorage<T>(key: string, defaultValue: T) {
return atom<T>({
key,
default: defaultValue,
effects_UNSTABLE: [
({ setSelf, onSet }) => {
const savedValue = localStorage.getItem(key);
if (savedValue !== null) {
try {
const parsedValue = JSON.parse(savedValue);
setSelf(parsedValue);
} catch (e) {
console.error(
`Error parsing localStorage key "${key}", \`savedValue\`: defaultValue, error:`,
e,
);
localStorage.setItem(key, JSON.stringify(defaultValue));
setSelf(defaultValue);
}
}
onSet((newValue: T) => {
localStorage.setItem(key, JSON.stringify(newValue));
});
},
],
});
}
|