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
This commit is contained in:
stacksmash76 2023-09-10 19:25:12 +02:00 committed by GitHub
parent 528405d1cb
commit ac4892dd09
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -53,33 +53,23 @@ function ContextMerger<T extends {}>(
defaults: T, defaults: T,
ctxState: StateWithValue<T> ctxState: StateWithValue<T>
) { ) {
let values = defaults;
const storage = localStorage.getItem(key); const storage = localStorage.getItem(key);
if (!storage) { if (storage) {
// Nothing to do. We already have a value thanks to react-ridge-state. try {
return; const json = JSON.parse(storage);
} if (json === null) {
console.warn(`JSON localStorage value for '${key}' context state is null`);
try { } else {
const json = JSON.parse(storage); values = { ...defaults, ...json };
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];
} }
}); } catch (e) {
console.error(`Failed to merge ${key} context state: ${e}`);
ctxState.set(json); }
} catch (e) {
console.error(`Failed to merge ${key} context state: ${e}`);
} }
ctxState.set(values);
} }
export const InitializeGlobalContext = () => { export const InitializeGlobalContext = () => {