| import { useState, useEffect } from 'react'; |
|
|
| |
| export function useLocalStorage<T>(key: string, initialValue: T): [T, React.Dispatch<React.SetStateAction<T>>] { |
| |
| |
| const storageKey = `yuki-app-${key}`; |
|
|
| const [storedValue, setStoredValue] = useState<T>(() => { |
| try { |
| if (typeof window === 'undefined') return initialValue; |
| const item = window.localStorage.getItem(storageKey); |
| return item ? JSON.parse(item) : initialValue; |
| } catch (error) { |
| console.error(error); |
| return initialValue; |
| } |
| }); |
|
|
| useEffect(() => { |
| try { |
| const item = window.localStorage.getItem(storageKey); |
| if (item) { |
| setStoredValue(JSON.parse(item)); |
| } |
| } catch (error) { |
| console.error(error); |
| } |
| }, [storageKey]); |
|
|
|
|
| const setValue: React.Dispatch<React.SetStateAction<T>> = (value) => { |
| try { |
| const valueToStore = value instanceof Function ? value(storedValue) : value; |
| setStoredValue(valueToStore); |
| if (typeof window !== 'undefined') { |
| window.localStorage.setItem(storageKey, JSON.stringify(valueToStore)); |
| } |
| } catch (error) { |
| console.error(error); |
| } |
| }; |
| return [storedValue, setValue]; |
| } |