Skip to content

Commit 0ab6e78

Browse files
committed
feat: handle zod parse errors by using safeParse
If there is an existing localStorage entry for `key`, the library should not throw an error, but replace the existing `localStorage` entry with the `initialValue`. This allows users of this library to modify stores with new schemas with ease.
1 parent e8ab834 commit 0ab6e78

File tree

1 file changed

+4
-4
lines changed

1 file changed

+4
-4
lines changed

src/index.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -39,14 +39,14 @@ export default function storedWritable<
3939
return;
4040
}
4141

42-
w.set(schema.parse(JSON.parse(event.newValue)));
42+
const { success, data } = schema.safeParse(JSON.parse(event.newValue));
43+
w.set(success ? data : initialValue);
4344
}
4445
});
4546
}
4647

47-
const w = writable<S>(
48-
stored ? schema.parse(JSON.parse(stored)) : initialValue
49-
);
48+
const parsed = stored ? schema.safeParse(JSON.parse(stored)) : null;
49+
const w = writable<S>(parsed?.success ? parsed.data : initialValue);
5050

5151
/**
5252
* Set writable value and inform subscribers. Updates the writeable's stored data in

0 commit comments

Comments
 (0)