mirror of
https://github.com/idanoo/autobrr
synced 2025-07-23 16:59:12 +00:00
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:
parent
528405d1cb
commit
ac4892dd09
1 changed files with 14 additions and 24 deletions
|
@ -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 = () => {
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue