Skip to content
This repository has been archived by the owner on Jun 2, 2024. It is now read-only.

Commit

Permalink
Bugfix: [web] Fix crash when persistence is invalid (#18)
Browse files Browse the repository at this point in the history
  • Loading branch information
maxijonson committed May 19, 2023
1 parent 1d4a054 commit d4e09fb
Showing 1 changed file with 44 additions and 1 deletion.
45 changes: 44 additions & 1 deletion packages/web/src/hooks/useStorage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,40 @@ export default <T,>(
const result = schema.safeParse(value);
setValidated(true);
if (result.success || warns.has(key)) return;

const {
error: { issues },
} = result;
const invalidTypeIssues = issues.filter(
(i) => i.code === "invalid_type"
);
if (
invalidTypeIssues.length > 0 &&
defaultValue &&
typeof defaultValue === "object" &&
value &&
typeof value === "object"
) {
// Attempt to fix undefined values
const repaired = invalidTypeIssues.reduce(
(repairedValue, issue) => {
const path = issue.path.join(".");
const pathValue = (value as Record<string, unknown>)[
path
];
const pathDefaultValue = (
defaultValue as Record<string, unknown>
)[path];
if (pathValue !== undefined) return repairedValue; // We're only interested in undefined values
(repairedValue as any)[path] = pathDefaultValue;
return repairedValue;
},
{ ...value }
);
setValue(repaired);
return;
}

warns.add(key);
console.error(result.error.format());
notifications.show({
Expand Down Expand Up @@ -56,7 +90,16 @@ export default <T,>(
autoClose: false,
});
}
}, [isValueLoaded, key, removeValue, schema, validated, value]);
}, [
defaultValue,
isValueLoaded,
key,
removeValue,
schema,
setValue,
validated,
value,
]);

return {
value,
Expand Down

0 comments on commit d4e09fb

Please sign in to comment.