1
0
Fork 0
freesewing/sites/shared/hooks/useLocalStorage.js

41 lines
1.2 KiB
JavaScript
Raw Normal View History

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_'
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
const [ready, setReady] = useState(false);
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
useEffect(() => {
readyInternal.current = true;
const item = window.localStorage.getItem(prefix + key)
if (item) {
2022-06-06 13:24:38 -05:00
setValue(JSON.parse(item));
} else if (storedValue) {
setValue(storedValue)
}
setReady(true);
}, [])
return [storedValue, setValue, ready]
2021-12-11 14:04:05 +01:00
}
export default useLocalStorage