mirror of
https://github.com/danny-avila/LibreChat.git
synced 2025-12-17 08:50:15 +01:00
⚛️ fix(atomWithLocalStorage): Handle Parsing Error (#2883)
This commit is contained in:
parent
eb5733083e
commit
c704a23749
1 changed files with 12 additions and 4 deletions
|
|
@ -6,16 +6,24 @@ import type { TOptionSettings } from '~/common';
|
||||||
function atomWithLocalStorage<T>(key: string, defaultValue: T) {
|
function atomWithLocalStorage<T>(key: string, defaultValue: T) {
|
||||||
return atom<T>({
|
return atom<T>({
|
||||||
key,
|
key,
|
||||||
default: defaultValue, // Set the default value directly
|
default: defaultValue,
|
||||||
effects_UNSTABLE: [
|
effects_UNSTABLE: [
|
||||||
({ setSelf, onSet }) => {
|
({ setSelf, onSet }) => {
|
||||||
// Load the initial value from localStorage if it exists
|
|
||||||
const savedValue = localStorage.getItem(key);
|
const savedValue = localStorage.getItem(key);
|
||||||
if (savedValue !== null) {
|
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) => {
|
onSet((newValue: T) => {
|
||||||
localStorage.setItem(key, JSON.stringify(newValue));
|
localStorage.setItem(key, JSON.stringify(newValue));
|
||||||
});
|
});
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue