From 90af13e2a985f26dbb92ecb8a2676b8a28c7242f Mon Sep 17 00:00:00 2001 From: Stefano Pigozzi <256895@studenti.unimore.it> Date: Tue, 27 Apr 2021 16:09:09 +0200 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20Fix=20#98=20by=20loading=20from?= =?UTF-8?q?=20localStorage=20without=20using=20an=20effect?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/hooks/useLocalStorageState.js | 50 +++++++------------ 1 file changed, 17 insertions(+), 33 deletions(-) diff --git a/code/frontend/src/hooks/useLocalStorageState.js b/code/frontend/src/hooks/useLocalStorageState.js index 1acc7ba..4734666 100644 --- a/code/frontend/src/hooks/useLocalStorageState.js +++ b/code/frontend/src/hooks/useLocalStorageState.js @@ -1,37 +1,34 @@ -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}. */ 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. */ - const load = useCallback( - () => { - if(localStorage) { - console.debug(`Loading ${key} from localStorage...`) - let _value = JSON.parse(localStorage.getItem(key)) + 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 - } - else { - console.info(`There is no value ${key} stored, defaulting...`) - return def - } + if(_value) { + console.info(`Loaded ${key} from localStorage!`) + return _value } else { - console.warn(`Can't load value as localStorage doesn't seem to be available, defaulting...`) + console.info(`There is no value ${key} stored, defaulting...`) return def } - }, - [key, def] - ) + } + else { + console.warn(`Can't load value as localStorage doesn't seem to be available, defaulting...`) + return def + } + } + + const [value, setValue] = useState(load()); /** * Save a value to the {@link localStorage}. @@ -60,18 +57,5 @@ export default function useLocalStorageState(key, def) { [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] } \ No newline at end of file