From 2a954932df507ebc39cd856b3a52197880970889 Mon Sep 17 00:00:00 2001 From: Jochen Klar Date: Thu, 30 Jan 2025 18:07:48 +0100 Subject: [PATCH] Refactor and fix useLsState --- rdmo/core/assets/js/hooks/useLsState.js | 27 +++++++++++++++---------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/rdmo/core/assets/js/hooks/useLsState.js b/rdmo/core/assets/js/hooks/useLsState.js index de81de45b4..6456308c5f 100644 --- a/rdmo/core/assets/js/hooks/useLsState.js +++ b/rdmo/core/assets/js/hooks/useLsState.js @@ -16,11 +16,22 @@ const useLsState = (path, initialValue, omit = []) => { localStorage.setItem(path, JSON.stringify(data)) } - // get the value from the local storage - const lsValue = getLs(path) + const getInitialState = () => { + // get the value from the local storage + const lsValue = getLs(path) + + // return the state with the value from the local storage or the provided initialValue + if (isPlainObject(lsValue)) { + return { ...initialValue, ...lsValue } + } else if (isEmpty(lsValue)) { + return initialValue + } else { + return lsValue + } + } - // setup the state with the value from the local storage or the provided initialValue - const [value, setValue] = useState(isEmpty(lsValue) ? initialValue : lsValue) + // setup the state + const [value, setValue] = useState(getInitialState()) return [ value, @@ -28,13 +39,7 @@ const useLsState = (path, initialValue, omit = []) => { setLs(path, value) setValue(value) }, - () => { - if (isPlainObject(initialValue)) { - setValue({ ...initialValue, ...getLs(path) }) - } else { - setValue(initialValue) - } - } + () => setValue(getInitialState()) ] }