parent
d72b8526a2
commit
b51c8c1fa4
@ -1,36 +1,115 @@ |
|||||||
import { useState } from 'react' |
// import { useState } from 'react'
|
||||||
|
|
||||||
|
// // Hook
|
||||||
|
// export const useLocalStorage = (key: string, initialValue: any) => {
|
||||||
|
// // State to store our value
|
||||||
|
// // Pass initial state function to useState so logic is only executed once
|
||||||
|
// const [storedValue, setStoredValue] = useState<any>(() => {
|
||||||
|
// try {
|
||||||
|
// // Get from local storage by key
|
||||||
|
// const item = window.localStorage.getItem(key)
|
||||||
|
// // Parse stored json or if none return initialValue
|
||||||
|
// return item ? JSON.parse(item) : initialValue
|
||||||
|
// } catch (error) {
|
||||||
|
// // If error also return initialValue
|
||||||
|
// console.log(error)
|
||||||
|
// return initialValue
|
||||||
|
// }
|
||||||
|
// })
|
||||||
|
// // Return a wrapped version of useState's setter function that ...
|
||||||
|
// // ... persists the new value to localStorage.
|
||||||
|
// const setValue = (value: any | ((val: any) => any)) => {
|
||||||
|
// try {
|
||||||
|
// // Allow value to be a function so we have same API as useState
|
||||||
|
// const valueToStore =
|
||||||
|
// value instanceof Function ? value(storedValue) : value
|
||||||
|
// // Save state
|
||||||
|
// setStoredValue(valueToStore)
|
||||||
|
// // Save to local storage
|
||||||
|
// window.localStorage.setItem(key, JSON.stringify(valueToStore))
|
||||||
|
// } catch (error) {
|
||||||
|
// // A more advanced implementation would handle the error case
|
||||||
|
// console.log(error)
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
// return [storedValue, setValue] as const
|
||||||
|
// }
|
||||||
|
|
||||||
|
import { Dispatch, SetStateAction, useEffect, useState } from 'react' |
||||||
|
|
||||||
|
type SetValue<T> = Dispatch<SetStateAction<T>> |
||||||
|
|
||||||
|
function useLocalStorage<T> (key: string, initialValue: T): [T, SetValue<T>] { |
||||||
|
// Get from local storage then
|
||||||
|
// parse stored json or return initialValue
|
||||||
|
const readValue = (): T => { |
||||||
|
// Prevent build error "window is undefined" but keep keep working
|
||||||
|
if (typeof window === 'undefined') { |
||||||
|
return initialValue |
||||||
|
} |
||||||
|
|
||||||
// Hook
|
|
||||||
export const useLocalStorage = (key: string, initialValue: any) => { |
|
||||||
// State to store our value
|
|
||||||
// Pass initial state function to useState so logic is only executed once
|
|
||||||
const [storedValue, setStoredValue] = useState<any>(() => { |
|
||||||
try { |
try { |
||||||
// Get from local storage by key
|
|
||||||
const item = window.localStorage.getItem(key) |
const item = window.localStorage.getItem(key) |
||||||
// Parse stored json or if none return initialValue
|
return item ? (JSON.parse(item) as T) : initialValue |
||||||
return item ? JSON.parse(item) : initialValue |
|
||||||
} catch (error) { |
} catch (error) { |
||||||
// If error also return initialValue
|
console.warn(`Error reading localStorage key “${key}”:`, error) |
||||||
console.log(error) |
|
||||||
return initialValue |
return initialValue |
||||||
} |
} |
||||||
}) |
} |
||||||
|
|
||||||
|
// State to store our value
|
||||||
|
// Pass initial state function to useState so logic is only executed once
|
||||||
|
const [storedValue, setStoredValue] = useState<T>(readValue) |
||||||
|
|
||||||
// Return a wrapped version of useState's setter function that ...
|
// Return a wrapped version of useState's setter function that ...
|
||||||
// ... persists the new value to localStorage.
|
// ... persists the new value to localStorage.
|
||||||
const setValue = (value: any | ((val: any) => any)) => { |
const setValue: SetValue<T> = value => { |
||||||
|
// Prevent build error "window is undefined" but keeps working
|
||||||
|
if (typeof window === 'undefined') { |
||||||
|
console.warn( |
||||||
|
`Tried setting localStorage key “${key}” even though environment is not a client` |
||||||
|
) |
||||||
|
} |
||||||
|
|
||||||
try { |
try { |
||||||
// Allow value to be a function so we have same API as useState
|
// Allow value to be a function so we have the same API as useState
|
||||||
const valueToStore = |
const newValue = value instanceof Function ? value(storedValue) : value |
||||||
value instanceof Function ? value(storedValue) : value |
|
||||||
// Save state
|
|
||||||
setStoredValue(valueToStore) |
|
||||||
// Save to local storage
|
// Save to local storage
|
||||||
window.localStorage.setItem(key, JSON.stringify(valueToStore)) |
window.localStorage.setItem(key, JSON.stringify(newValue)) |
||||||
|
|
||||||
|
// Save state
|
||||||
|
setStoredValue(newValue) |
||||||
|
|
||||||
|
// We dispatch a custom event so every useLocalStorage hook are notified
|
||||||
|
window.dispatchEvent(new Event('local-storage')) |
||||||
} catch (error) { |
} catch (error) { |
||||||
// A more advanced implementation would handle the error case
|
console.warn(`Error setting localStorage key “${key}”:`, error) |
||||||
console.log(error) |
|
||||||
} |
} |
||||||
} |
} |
||||||
return [storedValue, setValue] as const |
|
||||||
|
useEffect(() => { |
||||||
|
setStoredValue(readValue()) |
||||||
|
}, []) |
||||||
|
|
||||||
|
useEffect(() => { |
||||||
|
const handleStorageChange = () => { |
||||||
|
setStoredValue(readValue()) |
||||||
|
} |
||||||
|
|
||||||
|
// this only works for other documents, not the current one
|
||||||
|
window.addEventListener('storage', handleStorageChange) |
||||||
|
|
||||||
|
// this is a custom event, triggered in writeValueToLocalStorage
|
||||||
|
window.addEventListener('local-storage', handleStorageChange) |
||||||
|
|
||||||
|
return () => { |
||||||
|
window.removeEventListener('storage', handleStorageChange) |
||||||
|
window.removeEventListener('local-storage', handleStorageChange) |
||||||
|
} |
||||||
|
}, []) |
||||||
|
|
||||||
|
return [storedValue, setValue] |
||||||
} |
} |
||||||
|
|
||||||
|
export default useLocalStorage |
||||||
|
@ -1,15 +0,0 @@ |
|||||||
{ |
|
||||||
"extends": "./tsconfig.json", |
|
||||||
"compilerOptions": { |
|
||||||
"outDir": "../../../dist/out-tsc", |
|
||||||
"module": "commonjs", |
|
||||||
"types": ["jest", "node"] |
|
||||||
}, |
|
||||||
"include": [ |
|
||||||
"**/*.spec.ts", |
|
||||||
"**/*.spec.tsx", |
|
||||||
"**/*.spec.js", |
|
||||||
"**/*.spec.jsx", |
|
||||||
"**/*.d.ts" |
|
||||||
] |
|
||||||
} |
|
Loading…
Reference in new issue