1
Fork 0
mirror of https://github.com/pds-nest/nest.git synced 2024-11-25 22:44:19 +00:00

🐛 Fix #98 by loading from localStorage without using an effect

This commit is contained in:
Stefano Pigozzi 2021-04-27 16:09:09 +02:00
parent aa1b0dc748
commit 90af13e2a9
Signed by untrusted user who does not match committer: steffo
GPG key ID: 6965406171929D01

View file

@ -1,17 +1,14 @@
import { useCallback, useEffect, useState } from "react" import { useCallback, useState } from "react"
/** /**
* Hook with the same API as {@link React.useState} which stores its value in the browser's {@link localStorage}. * Hook with the same API as {@link React.useState} which stores its value in the browser's {@link localStorage}.
*/ */
export default function useLocalStorageState(key, def) { export default function useLocalStorageState(key, def) {
const [value, setValue] = useState(null);
/** /**
* Load the `key` from the {@link localStorage} into `value`, defaulting to `def` if it is not found. * Load the `key` from the {@link localStorage} into `value`, defaulting to `def` if it is not found.
*/ */
const load = useCallback( const load = () => {
() => {
if(localStorage) { if(localStorage) {
console.debug(`Loading ${key} from localStorage...`) console.debug(`Loading ${key} from localStorage...`)
let _value = JSON.parse(localStorage.getItem(key)) let _value = JSON.parse(localStorage.getItem(key))
@ -29,9 +26,9 @@ export default function useLocalStorageState(key, def) {
console.warn(`Can't load value as localStorage doesn't seem to be available, defaulting...`) console.warn(`Can't load value as localStorage doesn't seem to be available, defaulting...`)
return def return def
} }
}, }
[key, def]
) const [value, setValue] = useState(load());
/** /**
* Save a value to the {@link localStorage}. * Save a value to the {@link localStorage}.
@ -60,18 +57,5 @@ export default function useLocalStorageState(key, def) {
[setValue, save] [setValue, save]
) )
/*
* When the component first renders, try to load the value from the localStorage.
*/
useEffect(
() => {
if(!value) {
console.debug(`This is the first render, loading ${key} from the localStorage...`)
setValue(load())
}
},
[value, setValue, load, key],
)
return [value, setAndSave] return [value, setAndSave]
} }