2023-02-13 16:44:12 -06:00
|
|
|
import { useState, useEffect } from 'react'
|
|
|
|
|
|
|
|
const prefix = 'fs_'
|
2021-12-11 14:04:05 +01:00
|
|
|
|
|
|
|
// See: https://usehooks.com/useLocalStorage/
|
2023-02-13 16:44:12 -06:00
|
|
|
export function useLocalStorage(key, 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
|
2023-02-13 16:44:12 -06:00
|
|
|
// and for making sure we don't write the initial value over the current value
|
2023-01-29 18:57:24 +01:00
|
|
|
const [ready, setReady] = useState(false)
|
2023-02-13 16:44:12 -06:00
|
|
|
|
|
|
|
// State to store our value
|
|
|
|
const [storedValue, setValue] = useState(initialValue)
|
2022-06-07 12:36:27 -05:00
|
|
|
|
2022-06-22 15:19:07 -05:00
|
|
|
// set to localstorage every time the storedValue changes
|
2023-02-13 16:44:12 -06:00
|
|
|
// we do it this way instead of a callback because
|
|
|
|
// getting the current state inside `useCallback` didn't seem to be working
|
2022-06-22 15:19:07 -05:00
|
|
|
useEffect(() => {
|
2023-02-13 16:44:12 -06:00
|
|
|
if (ready) {
|
2022-06-22 15:19:07 -05:00
|
|
|
window.localStorage.setItem(prefix + key, JSON.stringify(storedValue))
|
2021-12-11 14:04:05 +01:00
|
|
|
}
|
2023-02-13 16:44:12 -06:00
|
|
|
}, [storedValue, key, ready])
|
2021-12-11 14:04:05 +01:00
|
|
|
|
2023-02-13 16:44:12 -06:00
|
|
|
// read from local storage on mount
|
2022-05-31 15:24:39 -04:00
|
|
|
useEffect(() => {
|
2023-02-13 16:44:12 -06:00
|
|
|
try {
|
|
|
|
// Get from local storage by key
|
|
|
|
const item = window.localStorage.getItem(prefix + key)
|
|
|
|
// Parse stored json or if none return initialValue
|
|
|
|
const valToSet = item ? JSON.parse(item) : initialValue
|
|
|
|
setValue(valToSet)
|
|
|
|
setReady(true)
|
|
|
|
} catch (error) {
|
|
|
|
console.log(error)
|
2022-05-31 15:24:39 -04:00
|
|
|
}
|
2023-03-12 17:59:43 +01:00
|
|
|
}, []) // The linter will hate this, but this was cleared to stop a render loop
|
2022-05-31 15:24:39 -04:00
|
|
|
|
|
|
|
return [storedValue, setValue, ready]
|
2021-12-11 14:04:05 +01:00
|
|
|
}
|