Skip to content

Commit

Permalink
Fix window is not defined
Browse files Browse the repository at this point in the history
  • Loading branch information
MattPereira committed Aug 2, 2024
1 parent 5b1f74a commit 154caf1
Showing 1 changed file with 19 additions and 6 deletions.
25 changes: 19 additions & 6 deletions packages/nextjs/hooks/common/useLocalStorage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,27 @@
import { useEffect, useState } from "react";

export const useLocalStorage = <T>(key: string, defaultValue: T) => {
const [state, setState] = useState<T>(() => {
const savedValue = window.localStorage.getItem(key);
return savedValue ? JSON.parse(savedValue) : defaultValue;
});
const [state, setState] = useState<T>(defaultValue);
const [hasMounted, setHasMounted] = useState(false);

useEffect(() => {
window.localStorage.setItem(key, JSON.stringify(state));
}, [key, state]);
setHasMounted(true);
}, []);

useEffect(() => {
if (hasMounted) {
const savedValue = window.localStorage.getItem(key);
if (savedValue) {
setState(JSON.parse(savedValue));
}
}
}, [hasMounted, key]);

useEffect(() => {
if (hasMounted) {
window.localStorage.setItem(key, JSON.stringify(state));
}
}, [key, state, hasMounted]);

return [state, setState] as const;
};

0 comments on commit 154caf1

Please sign in to comment.