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

39 lines
1.2 KiB
JavaScript
Raw Normal View History

2022-06-22 15:38:15 -05:00
import { useState, useEffect, useRef, useReducer } from 'react'
2021-12-11 14:04:05 +01:00
// See: https://usehooks.com/useLocalStorage/
export function useLocalStorage(key, initialValue, reducer) {
2021-12-11 14:04:05 +01:00
const prefix = 'fs_'
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
const [ready, setReady] = useState(false)
const readyInternal = useRef(false)
const setValue = setStoredValue
// 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
}
}, [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
useEffect(() => {
readyInternal.current = true
const item = window.localStorage.getItem(prefix + key)
let valueToSet = storedValue
if (item) {
valueToSet = JSON.parse(item)
}
if (reducer) {
valueToSet = { value: valueToSet, type: 'replace' }
}
setValue(valueToSet)
setReady(true)
}, [])
return [storedValue, setValue, ready]
2021-12-11 14:04:05 +01:00
}