From b0aa9c97e95dd08a34d624df84eca3c6b6b04873 Mon Sep 17 00:00:00 2001 From: MURAGEH Date: Sun, 5 Mar 2023 01:31:38 +0300 Subject: [PATCH 1/2] return default values only if they don't exist in storage do not crash if storage value is undefined --- README.md | 2 +- src/hooks/saveProgress/useProgress.ts | 11 ++++++++++- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index bedd546..210d730 100644 --- a/README.md +++ b/README.md @@ -163,7 +163,7 @@ const MyFormComponent = () => { validate={values => { const errors = {}; if (values.name.length < 1) { - errors.token = 'Enter a name.'; + errors.name = 'Enter a name.'; } return errors; }} diff --git a/src/hooks/saveProgress/useProgress.ts b/src/hooks/saveProgress/useProgress.ts index 8a1bf97..abb7164 100644 --- a/src/hooks/saveProgress/useProgress.ts +++ b/src/hooks/saveProgress/useProgress.ts @@ -42,17 +42,26 @@ function useProgress({ clearFunction, forceLocalActions = false }: useProgressProps) { + const [initialized, setInitialized] = React.useState(false); const [values, setValues] = React.useState(initialValues); React.useEffect(() => { if (typeof window !== 'undefined') { const saved = (storage ?? window.localStorage).getItem(key); - const initialValue: T = JSON.parse(saved!); + let initialValue: T; + try { + initialValue = JSON.parse(saved!); + } catch (e) { + initialValue = {} as T; + } setValues(initialValue || initialValues || {} as T); + saveValues(values); + setInitialized(true); } }, []); React.useEffect(() => { + if (!initialized) return; saveValues(values); }, [values]); From 82fe032305ea45f1184c0ead1f73023d1f3c5410 Mon Sep 17 00:00:00 2001 From: MURAGEH Date: Sun, 5 Mar 2023 01:32:07 +0300 Subject: [PATCH 2/2] 1.0.11 --- package-lock.json | 4 ++-- package.json | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/package-lock.json b/package-lock.json index 5c42ec4..4058189 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@crispice/save-progress", - "version": "1.0.10", + "version": "1.0.11", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "@crispice/save-progress", - "version": "1.0.10", + "version": "1.0.11", "license": "MIT", "dependencies": { "typescript": "^4.9.3" diff --git a/package.json b/package.json index 966d813..143f9dc 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@crispice/save-progress", - "version": "1.0.10", + "version": "1.0.11", "description": "A React hook to save progress in a form, or any other scenario, and restore it when the user returns to the form. It uses localStorage to save the progress.", "main": "dist/cjs/index.js", "module": "dist/esm/index.js",