Skip to content

Commit

Permalink
improve robusteness of file storage (fixes #147)
Browse files Browse the repository at this point in the history
  • Loading branch information
franciscoBSalgueiro committed Feb 9, 2024
1 parent 4751b97 commit e32d258
Showing 1 changed file with 16 additions and 8 deletions.
24 changes: 16 additions & 8 deletions src/atoms/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ export function createZodStorage<Value>(
return initialValue;
}
try {
return schema.parse(JSON.parse(storedValue ?? ""));
return schema.parse(JSON.parse(storedValue));
} catch {
warn(`Invalid value for ${key}: ${storedValue}`);
this.setItem(key, initialValue);
Expand All @@ -64,14 +64,22 @@ export function createAsyncZodStorage<Value>(
): AsyncStorage<Value> {
return {
async getItem(key, initialValue) {
const storedValue = await storage.getItem(key);
const res = schema.safeParse(JSON.parse(storedValue ?? ""));
if (res.success) {
return res.data;
try {
const storedValue = await storage.getItem(key);
if (storedValue === null) {
return initialValue;
}
const res = schema.safeParse(JSON.parse(storedValue));
if (res.success) {
return res.data;
}
warn(`Invalid value for ${key}: ${storedValue}\n${res.error}`);
await this.setItem(key, initialValue);
return initialValue;
} catch (error) {
warn(`Error getting ${key}: ${error}`);
return initialValue;
}
warn(`Invalid value for ${key}: ${storedValue}\n${res.error}`);
await this.setItem(key, initialValue);
return initialValue;
},
async setItem(key, value) {
storage.setItem(key, JSON.stringify(value, null, 4));
Expand Down

0 comments on commit e32d258

Please sign in to comment.