fix crash when localStorage full
This commit is contained in:
@@ -8,8 +8,7 @@ export function useLocalStorage(key, initValue) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (initValue) {
|
if (initValue) {
|
||||||
localStorage.setItem(key, initValue);
|
trySettingLocalStorage(key, initValue, setState);
|
||||||
window.dispatchEvent(new Event("storage"));
|
|
||||||
}
|
}
|
||||||
return initValue;
|
return initValue;
|
||||||
});
|
});
|
||||||
@@ -18,9 +17,8 @@ export function useLocalStorage(key, initValue) {
|
|||||||
if (!state || state === "undefined") {
|
if (!state || state === "undefined") {
|
||||||
localStorage.removeItem(key);
|
localStorage.removeItem(key);
|
||||||
} else {
|
} else {
|
||||||
localStorage.setItem(key, state);
|
trySettingLocalStorage(key, state, setState);
|
||||||
}
|
}
|
||||||
window.dispatchEvent(new Event("storage"));
|
|
||||||
}, [key, state]);
|
}, [key, state]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -32,8 +30,7 @@ export function useLocalStorage(key, initValue) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (initValue) {
|
if (initValue) {
|
||||||
localStorage.setItem(key, initValue);
|
trySettingLocalStorage(key, initValue, setState);
|
||||||
window.dispatchEvent(new Event("storage"));
|
|
||||||
}
|
}
|
||||||
return initValue;
|
return initValue;
|
||||||
});
|
});
|
||||||
@@ -44,3 +41,13 @@ export function useLocalStorage(key, initValue) {
|
|||||||
|
|
||||||
return [state, setState];
|
return [state, setState];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const trySettingLocalStorage = (key, value, setState) => {
|
||||||
|
try {
|
||||||
|
localStorage.setItem(key, value);
|
||||||
|
window.dispatchEvent(new Event("storage"));
|
||||||
|
} catch (e) {
|
||||||
|
console.error(e);
|
||||||
|
setState(value);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|||||||
Reference in New Issue
Block a user