Skip to content

Commit

Permalink
fix: useLocalStorage
Browse files Browse the repository at this point in the history
  • Loading branch information
evilpeach committed Jul 14, 2023
1 parent 96814a5 commit 89a18bb
Showing 1 changed file with 8 additions and 2 deletions.
10 changes: 8 additions & 2 deletions src/lib/hooks/useLocalStorage.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* eslint-disable no-console */
import type { Dispatch, SetStateAction } from "react";
import { useEffect, useState } from "react";

Expand All @@ -12,12 +13,17 @@ export const useLocalStorage = <T>(
const value = window.localStorage.getItem(key);
return value ? (JSON.parse(value) as T) : defaultValue;
} catch (e) {
return [] as T;
console.warn(`Error reading localStorage key “${key}”:`, e);
return defaultValue as T;
}
});

useEffect(() => {
window.localStorage.setItem(key, JSON.stringify(storedValue));
try {
window.localStorage.setItem(key, JSON.stringify(storedValue));
} catch (e) {
console.warn(`Error setting localStorage key “${key}”:`, e);
}
}, [key, storedValue]);

return [storedValue, setStoredValue];
Expand Down

0 comments on commit 89a18bb

Please sign in to comment.