2022-06-07 12:36:27 -05:00
|
|
|
import { useState, useEffect, useRef } from 'react'
|
2021-12-11 14:04:05 +01:00
|
|
|
|
|
|
|
// See: https://usehooks.com/useLocalStorage/
|
|
|
|
function useLocalStorage(key, initialValue) {
|
|
|
|
const prefix = 'fs_'
|
2022-05-31 15:24:39 -04:00
|
|
|
const [storedValue, setStoredValue] = 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);
|
|
|
|
|
|
|
|
const setValue = function (value) {
|
|
|
|
if (!readyInternal.current) {
|
|
|
|
return null
|
|
|
|
}
|
2021-12-11 14:04:05 +01:00
|
|
|
|
|
|
|
try {
|
|
|
|
const valueToStore = value instanceof Function ? value(storedValue) : value
|
|
|
|
setStoredValue(valueToStore)
|
|
|
|
window.localStorage.setItem(prefix + key, JSON.stringify(valueToStore))
|
|
|
|
} catch (error) {
|
|
|
|
console.log(error)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
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)
|
|
|
|
if (item) {
|
2022-06-06 13:24:38 -05:00
|
|
|
setValue(JSON.parse(item));
|
2022-06-07 12:36:27 -05:00
|
|
|
} else if (storedValue) {
|
|
|
|
setValue(storedValue)
|
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
|