Spaces:
Build error
Build error
| 'use client'; | |
| import { useState, useEffect } from 'react'; | |
| export function useLocalStorage<T>(key: string, initialValue: T): [T, (value: T | ((val: T) => T)) => void] { | |
| const [storedValue, setStoredValue] = useState<T>(initialValue); | |
| useEffect(() => { | |
| try { | |
| const item = window.localStorage.getItem(key); | |
| if (item) { | |
| setStoredValue(JSON.parse(item)); | |
| } | |
| } catch (error) { | |
| console.error(error); | |
| // If error, we stick to the initial value | |
| } | |
| }, [key]); | |
| const setValue = (value: T | ((val: T) => T)) => { | |
| try { | |
| const valueToStore = | |
| value instanceof Function ? value(storedValue) : value; | |
| setStoredValue(valueToStore); | |
| if (typeof window !== 'undefined') { | |
| window.localStorage.setItem(key, JSON.stringify(valueToStore)); | |
| } | |
| } catch (error) { | |
| console.error(error); | |
| } | |
| }; | |
| return [storedValue, setValue]; | |
| } | |