2021-04-27 14:09:09 +00:00
|
|
|
import { useCallback, useState } from "react"
|
2021-04-25 15:22:52 +00:00
|
|
|
|
|
|
|
|
|
|
|
/**
|
2021-05-22 02:44:08 +00:00
|
|
|
* Hook with the same API as {@link React.useState} which additionally stores its value in the browser's
|
|
|
|
* {@link localStorage}.
|
2021-04-25 15:22:52 +00:00
|
|
|
*/
|
|
|
|
export default function useLocalStorageState(key, def) {
|
2021-04-26 20:08:52 +00:00
|
|
|
/**
|
|
|
|
* Load the `key` from the {@link localStorage} into `value`, defaulting to `def` if it is not found.
|
|
|
|
*/
|
2021-04-27 14:09:09 +00:00
|
|
|
const load = () => {
|
|
|
|
if(localStorage) {
|
|
|
|
console.debug(`Loading ${key} from localStorage...`)
|
|
|
|
let _value = JSON.parse(localStorage.getItem(key))
|
|
|
|
|
|
|
|
if(_value) {
|
|
|
|
console.info(`Loaded ${key} from localStorage!`)
|
|
|
|
return _value
|
2021-04-25 15:22:52 +00:00
|
|
|
}
|
|
|
|
else {
|
2021-04-27 14:09:09 +00:00
|
|
|
console.info(`There is no value ${key} stored, defaulting...`)
|
2021-04-25 15:22:52 +00:00
|
|
|
return def
|
|
|
|
}
|
2021-04-27 14:09:09 +00:00
|
|
|
}
|
|
|
|
else {
|
|
|
|
console.warn(`Can't load value as localStorage doesn't seem to be available, defaulting...`)
|
|
|
|
return def
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-05-11 14:37:15 +00:00
|
|
|
const [value, setValue] = useState(load())
|
2021-04-26 20:08:52 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Save a value to the {@link localStorage}.
|
|
|
|
*/
|
|
|
|
const save = useCallback(
|
2021-05-23 16:25:17 +00:00
|
|
|
val => {
|
2021-04-26 20:08:52 +00:00
|
|
|
if(localStorage) {
|
|
|
|
console.debug(`Saving ${key} to localStorage...`)
|
2021-05-23 16:25:17 +00:00
|
|
|
localStorage.setItem(key, JSON.stringify(val))
|
2021-04-26 20:08:52 +00:00
|
|
|
}
|
|
|
|
else {
|
|
|
|
console.warn(`Can't save ${key}; localStorage doesn't seem to be available...`)
|
|
|
|
}
|
|
|
|
},
|
2021-05-11 14:37:15 +00:00
|
|
|
[key],
|
2021-04-26 20:08:52 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Set `value` and save it to the {@link localStorage}.
|
|
|
|
*/
|
|
|
|
const setAndSave = useCallback(
|
2021-05-23 16:25:17 +00:00
|
|
|
val => {
|
|
|
|
setValue(val)
|
|
|
|
save(val)
|
2021-04-26 20:08:52 +00:00
|
|
|
},
|
2021-05-11 14:37:15 +00:00
|
|
|
[save],
|
2021-04-26 20:08:52 +00:00
|
|
|
)
|
|
|
|
|
2021-04-25 15:22:52 +00:00
|
|
|
return [value, setAndSave]
|
|
|
|
}
|