2021-09-29 07:26:00 -04:00
|
|
|
import { useState, useCallback, useEffect } from 'react'
|
2021-05-18 06:56:56 -04:00
|
|
|
import localStorage from '../../infrastructure/local-storage'
|
2021-01-07 09:22:40 -05:00
|
|
|
|
2021-09-29 07:26:00 -04:00
|
|
|
/**
|
|
|
|
* @param {string} key
|
|
|
|
* @param {any} [defaultValue]
|
|
|
|
* @param {boolean} [listen]
|
|
|
|
*
|
|
|
|
* @returns {[any, function]}
|
|
|
|
*/
|
|
|
|
function usePersistedState(key, defaultValue, listen = false) {
|
2021-01-07 09:22:40 -05:00
|
|
|
const [value, setValue] = useState(() => {
|
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.
|
|
|
|
setValue(localStorage.getItem(key))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
window.addEventListener('storage', listener)
|
|
|
|
|
|
|
|
return () => {
|
|
|
|
window.removeEventListener('storage', listener)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}, [key, listen])
|
|
|
|
|
2021-01-07 09:22:40 -05:00
|
|
|
return [value, updateFunction]
|
|
|
|
}
|
|
|
|
|
|
|
|
export default usePersistedState
|