Spaces:
Running
Running
| 'use client' | |
| import { useState, useEffect } from 'react' | |
| // Custom implementation of useKV hook for key-value storage | |
| export function useKV<T>(key: string, defaultValue: T): [T, (value: T) => void] { | |
| // Initialize state with the default value | |
| const [value, setValue] = useState<T>(() => { | |
| // Try to get the value from localStorage on initial load | |
| if (typeof window !== 'undefined') { | |
| try { | |
| const storedValue = localStorage.getItem(key) | |
| if (storedValue !== null) { | |
| return JSON.parse(storedValue) | |
| } | |
| } catch (error) { | |
| console.error(`Error reading from localStorage for key "${key}":`, error) | |
| } | |
| } | |
| return defaultValue | |
| }) | |
| // Update localStorage whenever the value changes | |
| useEffect(() => { | |
| if (typeof window !== 'undefined') { | |
| try { | |
| localStorage.setItem(key, JSON.stringify(value)) | |
| } catch (error) { | |
| console.error(`Error writing to localStorage for key "${key}":`, error) | |
| } | |
| } | |
| }, [key, value]) | |
| return [value, setValue] | |
| } | |
| export default useKV |