From ac4892dd098e4f4f9240f8fc704c67e6fced120c Mon Sep 17 00:00:00 2001 From: stacksmash76 <98354295+stacksmash76@users.noreply.github.com> Date: Sun, 10 Sep 2023 19:25:12 +0200 Subject: [PATCH] fix(web): improve initial context state (#1103) * fix(web): set initial context state correctly by triggering onSet callbacks * chore: simplified ContextMerger logic and avoided edge-cases --- web/src/utils/Context.ts | 38 ++++++++++++++------------------------ 1 file changed, 14 insertions(+), 24 deletions(-) diff --git a/web/src/utils/Context.ts b/web/src/utils/Context.ts index 7a27420..4eb96f9 100644 --- a/web/src/utils/Context.ts +++ b/web/src/utils/Context.ts @@ -53,33 +53,23 @@ function ContextMerger( defaults: T, ctxState: StateWithValue ) { + let values = defaults; + const storage = localStorage.getItem(key); - if (!storage) { - // Nothing to do. We already have a value thanks to react-ridge-state. - return; - } - - try { - const json = JSON.parse(storage); - if (json === null) { - console.warn(`JSON localStorage value for '${key}' context state is null`); - return; - } - - Object.keys(defaults).forEach((key) => { - const propName = key as unknown as keyof T; - - // Check if JSON in localStorage is missing newly added key - if (!Object.prototype.hasOwnProperty.call(json, key)) { - // ... and default-initialize it. - json[propName] = defaults[propName]; + if (storage) { + try { + const json = JSON.parse(storage); + if (json === null) { + console.warn(`JSON localStorage value for '${key}' context state is null`); + } else { + values = { ...defaults, ...json }; } - }); - - ctxState.set(json); - } catch (e) { - console.error(`Failed to merge ${key} context state: ${e}`); + } catch (e) { + console.error(`Failed to merge ${key} context state: ${e}`); + } } + + ctxState.set(values); } export const InitializeGlobalContext = () => {