fix crash when localStorage full

This commit is contained in:
NilsUeter
2024-04-05 17:03:19 +02:00
parent f3639cca3c
commit 54049b0d35
+13 -6
View File
@@ -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);
}
};