( key: string, initialValue: T, )
| 6 | * want that behavior, you should use this hook inside a Context object. |
| 7 | */ |
| 8 | export function useLocalStorage<T>( |
| 9 | key: string, |
| 10 | initialValue: T, |
| 11 | ): [T, (arg0: T) => void] { |
| 12 | // State to store our value |
| 13 | // Pass initial state function to useState so logic is only executed once |
| 14 | const [storedValue, setStoredValue] = useState(() => { |
| 15 | try { |
| 16 | // Get from local storage by key |
| 17 | const item = window.localStorage.getItem(key); |
| 18 | // Parse stored json or if none return initialValue |
| 19 | return item ? JSON.parse(item) : initialValue; |
| 20 | } catch (error) { |
| 21 | // If error also return initialValue |
| 22 | console.log(`Error finding ${key} in localStorage:`, error); |
| 23 | return initialValue; |
| 24 | } |
| 25 | }); |
| 26 | |
| 27 | // Return a wrapped version of useState's setter function that ... |
| 28 | // ... persists the new value to localStorage. |
| 29 | const setValue = (value: T | ((val: T) => T)) => { |
| 30 | try { |
| 31 | // Allow value to be a function so we have same API as useState |
| 32 | const valueToStore = |
| 33 | value instanceof Function ? value(storedValue) : value; |
| 34 | // Save state |
| 35 | setStoredValue(valueToStore); |
| 36 | // Save to local storage |
| 37 | window.localStorage.setItem(key, JSON.stringify(valueToStore)); |
| 38 | } catch (error) { |
| 39 | // A more advanced implementation would handle the error case |
| 40 | console.log(error); |
| 41 | } |
| 42 | }; |
| 43 | |
| 44 | return [storedValue, setValue]; |
| 45 | } |
no outgoing calls
no test coverage detected