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