2022-06-22 15:19:07 -05:00
|
|
|
import { useState, useEffect, useRef, useCallback, useReducer } from 'react'
|
2021-12-11 14:04:05 +01:00
|
|
|
|
|
|
|
// See: https://usehooks.com/useLocalStorage/
|
2022-06-22 15:19:07 -05:00
|
|
|
function useLocalStorage(key, initialValue, reducer) {
|
2021-12-11 14:04:05 +01:00
|
|
|
const prefix = 'fs_'
|
2022-06-22 15:19:07 -05:00
|
|
|
const [storedValue, setStoredValue] = typeof reducer == 'function' ? useReducer(reducer, initialValue) : useState(initialValue);
|
2022-06-06 13:20:24 -05:00
|
|
|
// use this to track whether it's mounted. useful for doing other effects outside this hook
|
2022-05-31 15:24:39 -04:00
|
|
|
const [ready, setReady] = useState(false);
|
2022-06-07 12:36:27 -05:00
|
|
|
const readyInternal = useRef(false);
|
2022-06-22 15:19:07 -05:00
|
|
|
const setValue = setStoredValue
|
2022-06-07 12:36:27 -05:00
|
|
|
|
2022-06-22 15:19:07 -05:00
|
|
|
// set to localstorage every time the storedValue changes
|
|
|
|
useEffect(() => {
|
|
|
|
if (readyInternal.current) {
|
|
|
|
window.localStorage.setItem(prefix + key, JSON.stringify(storedValue))
|
2021-12-11 14:04:05 +01:00
|
|
|
}
|
2022-06-22 15:19:07 -05:00
|
|
|
}, [storedValue])
|
2021-12-11 14:04:05 +01:00
|
|
|
|
2022-06-06 13:20:24 -05:00
|
|
|
// get the item from localstorage after the component has mounted. empty brackets mean it runs one time
|
2022-05-31 15:24:39 -04:00
|
|
|
useEffect(() => {
|
2022-06-07 12:36:27 -05:00
|
|
|
readyInternal.current = true;
|
2022-05-31 15:24:39 -04:00
|
|
|
const item = window.localStorage.getItem(prefix + key)
|
2022-06-22 15:19:07 -05:00
|
|
|
let valueToSet = storedValue;
|
2022-05-31 15:24:39 -04:00
|
|
|
if (item) {
|
2022-06-22 15:19:07 -05:00
|
|
|
valueToSet = JSON.parse(item)
|
2022-05-31 15:24:39 -04:00
|
|
|
}
|
2022-06-22 15:19:07 -05:00
|
|
|
|
|
|
|
if (reducer) {
|
|
|
|
valueToSet = {value: valueToSet, type: 'replace'}
|
|
|
|
}
|
|
|
|
|
|
|
|
setValue(valueToSet)
|
2022-05-31 15:24:39 -04:00
|
|
|
setReady(true);
|
|
|
|
}, [])
|
|
|
|
|
|
|
|
return [storedValue, setValue, ready]
|
2021-12-11 14:04:05 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
export default useLocalStorage
|