2022-04-26 07:26:37 -04:00
|
|
|
import {
|
|
|
|
useState,
|
|
|
|
useCallback,
|
|
|
|
useEffect,
|
|
|
|
SetStateAction,
|
|
|
|
Dispatch,
|
|
|
|
} from 'react'
|
2022-05-25 03:57:57 -04:00
|
|
|
import _ from 'lodash'
|
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(
|
2022-05-25 03:57:57 -04:00
|
|
|
(newValue: SetStateAction<T>) => {
|
2021-09-23 06:35:50 -04:00
|
|
|
setValue(value => {
|
2022-05-25 03:57:57 -04:00
|
|
|
const actualNewValue = _.isFunction(newValue)
|
|
|
|
? newValue(value)
|
|
|
|
: newValue
|
2021-09-23 06:35:50 -04:00
|
|
|
|
|
|
|
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) {
|
2022-05-26 05:39:07 -04:00
|
|
|
const listener = (event: StorageEvent) => {
|
2021-09-29 07:26:00 -04:00
|
|
|
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
|