2022-04-26 11:26:37 +00:00
|
|
|
import {
|
|
|
|
useState,
|
|
|
|
useCallback,
|
|
|
|
useEffect,
|
|
|
|
SetStateAction,
|
|
|
|
Dispatch,
|
|
|
|
} from 'react'
|
2021-05-18 10:56:56 +00:00
|
|
|
import localStorage from '../../infrastructure/local-storage'
|
2021-01-07 14:22:40 +00:00
|
|
|
|
2022-04-26 11:26:37 +00:00
|
|
|
function usePersistedState<T>(
|
|
|
|
key: string,
|
|
|
|
defaultValue?: T,
|
|
|
|
listen = false
|
|
|
|
): [T, Dispatch<SetStateAction<T>>] {
|
|
|
|
const [value, setValue] = useState<T>(() => {
|
2021-09-23 10:35:50 +00:00
|
|
|
return localStorage.getItem(key) ?? defaultValue
|
2021-01-07 14:22:40 +00:00
|
|
|
})
|
|
|
|
|
|
|
|
const updateFunction = useCallback(
|
|
|
|
newValue => {
|
2021-09-23 10:35:50 +00:00
|
|
|
setValue(value => {
|
|
|
|
const actualNewValue =
|
|
|
|
typeof newValue === 'function' ? newValue(value) : newValue
|
|
|
|
|
|
|
|
if (actualNewValue === defaultValue) {
|
|
|
|
localStorage.removeItem(key)
|
|
|
|
} else {
|
|
|
|
localStorage.setItem(key, actualNewValue)
|
|
|
|
}
|
|
|
|
|
|
|
|
return actualNewValue
|
|
|
|
})
|
2021-01-07 14:22:40 +00:00
|
|
|
},
|
|
|
|
[key, defaultValue]
|
|
|
|
)
|
|
|
|
|
2021-09-29 11:26:00 +00:00
|
|
|
useEffect(() => {
|
|
|
|
if (listen) {
|
|
|
|
const listener = event => {
|
|
|
|
if (event.key === key) {
|
|
|
|
// note: this value is read via getItem rather than from event.newValue
|
|
|
|
// because getItem handles deserializing the JSON that's stored in localStorage.
|
2022-03-31 11:22:36 +00:00
|
|
|
setValue(localStorage.getItem(key) ?? defaultValue)
|
2021-09-29 11:26:00 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
window.addEventListener('storage', listener)
|
|
|
|
|
|
|
|
return () => {
|
|
|
|
window.removeEventListener('storage', listener)
|
|
|
|
}
|
|
|
|
}
|
2022-03-31 11:22:36 +00:00
|
|
|
}, [key, listen, defaultValue])
|
2021-09-29 11:26:00 +00:00
|
|
|
|
2021-01-07 14:22:40 +00:00
|
|
|
return [value, updateFunction]
|
|
|
|
}
|
|
|
|
|
|
|
|
export default usePersistedState
|