Skip to content

Commit

Permalink
troubleshoot accessing localstorage within nextjs
Browse files Browse the repository at this point in the history
  • Loading branch information
MattPereira committed Aug 2, 2024
1 parent 14646ee commit 5b1f74a
Showing 1 changed file with 4 additions and 2 deletions.
6 changes: 4 additions & 2 deletions packages/nextjs/hooks/common/useLocalStorage.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
"use client";

import { useEffect, useState } from "react";

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

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

return [state, setState] as const;
Expand Down

0 comments on commit 5b1f74a

Please sign in to comment.