2022-04-26 07:26:37 -04:00
|
|
|
import {
|
|
|
|
useState,
|
|
|
|
useCallback,
|
|
|
|
useEffect,
|
|
|
|
SetStateAction,
|
|
|
|
Dispatch,
|
|
|
|
} from 'react'
|
2021-05-18 06:56:56 -04:00
|
|
|
import localStorage from '../../infrastructure/local-storage'
|
2021-01-07 09:22:40 -05:00
|
|
|
|
2022-04-26 07:26:37 -04:00
|
|
|
function usePersistedState<T>(
|
|
|
|
key: string,
|
|
|
|
defaultValue?: T,
|
|
|
|
listen = false
|
|
|
|
): [T, Dispatch<SetStateAction<T>>] {
|
|
|
|
const [value, setValue] = useState<T>(() => {
|
2021-09-23 06:35:50 -04:00
|
|
|
return localStorage.getItem(key) ?? defaultValue
|
2021-01-07 09:22:40 -05:00
|
|
|
})
|
|
|
|
|
|
|
|
const updateFunction = useCallback(
|
|
|
|
newValue => {
|
2021-09-23 06:35:50 -04: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 09:22:40 -05:00
|
|
|
},
|
|
|
|
[key, defaultValue]
|
|
|
|
)
|
|
|
|
|
2021-09-29 07:26:00 -04: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 07:22:36 -04:00
|
|
|
setValue(localStorage.getItem(key) ?? defaultValue)
|
2021-09-29 07:26:00 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
window.addEventListener('storage', listener)
|
|
|
|
|
|
|
|
return () => {
|
|
|
|
window.removeEventListener('storage', listener)
|
|
|
|
}
|
|
|
|
}
|
2022-03-31 07:22:36 -04:00
|
|
|
}, [key, listen, defaultValue])
|
2021-09-29 07:26:00 -04:00
|
|
|
|
2021-01-07 09:22:40 -05:00
|
|
|
return [value, updateFunction]
|
|
|
|
}
|
|
|
|
|
|
|
|
export default usePersistedState
|