Skip to content

Commit

Permalink
⚛️ fix(atomWithLocalStorage): Handle Parsing Error (#2883)
Browse files Browse the repository at this point in the history
  • Loading branch information
danny-avila authored May 28, 2024
1 parent eb57330 commit c704a23
Showing 1 changed file with 12 additions and 4 deletions.
16 changes: 12 additions & 4 deletions client/src/store/settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,24 @@ import type { TOptionSettings } from '~/common';
function atomWithLocalStorage<T>(key: string, defaultValue: T) {
return atom<T>({
key,
default: defaultValue, // Set the default value directly
default: defaultValue,
effects_UNSTABLE: [
({ setSelf, onSet }) => {
// Load the initial value from localStorage if it exists
const savedValue = localStorage.getItem(key);
if (savedValue !== null) {
setSelf(JSON.parse(savedValue));
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);
}
}

// Update localStorage whenever the atom's value changes
onSet((newValue: T) => {
localStorage.setItem(key, JSON.stringify(newValue));
});
Expand Down

0 comments on commit c704a23

Please sign in to comment.