Skip to content

Commit

Permalink
move local storage state initialization to useEffect to avoid hydrati…
Browse files Browse the repository at this point in the history
…on errors
  • Loading branch information
konstantin-lukas committed Sep 12, 2024
1 parent 30a26b6 commit f157c98
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 10 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "anzol",
"version": "2.6.0",
"version": "2.6.1",
"main": "dist/index.cjs.js",
"module": "dist/index.esm.js",
"types": "dist/index.d.ts",
Expand Down
22 changes: 13 additions & 9 deletions src/hooks/useLocalStorage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,24 +28,28 @@ export interface LocalStorageOptions {
* return <input type="text" value={value ?? ""} onChange={(e) => setValue(e.target.value)} />;
* }
* ```
*/
*/
function useLocalStorage(key: string, {
initialValue,
propagateChanges = false,
listenForChanges = false,
}: LocalStorageOptions = {}): [string | null, Dispatch<SetStateAction<string | null>>] {

const [value, setValue] = useState(() => {
if (typeof window === "undefined") return null;
const storedValue = localStorage.getItem(key);
if (storedValue) return storedValue;
const init = initialValue || null;
if (init) localStorage.setItem(key, init);
return init;
});
const [value, setValue] = useState<string | null>(null);
const [blockUpdates, setBlockUpdates] = useState(true);
const id = useId();

useEffect(() => {
if (typeof window === "undefined") return;
setValue(() => {
const storedValue = localStorage.getItem(key);
if (storedValue) return storedValue;
const init = initialValue || null;
if (init) localStorage.setItem(key, init);
return init;
});
}, [key, initialValue]);

useEffect(() => {
if (typeof window === "undefined") return;
if (!blockUpdates) {
Expand Down
5 changes: 5 additions & 0 deletions tests/useLocalStorage.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,11 @@ async function renderUseLocalStorage({
}

describe("useLocalStorage", () => {

afterEach(() => {
localStorage.clear();
});

test("should set a default value when local storage item doesn't exist", async () => {
const { result } = await renderUseLocalStorage({ initialKey: "animal", initialOptions: { initialValue: "Bear" }});
expect(result.current[0]).toBe("Bear");
Expand Down

0 comments on commit f157c98

Please sign in to comment.