Skip to content

Commit ec0e242

Browse files
committed
only restore form changes younger than an hour
1 parent 8770679 commit ec0e242

File tree

1 file changed

+29
-16
lines changed

1 file changed

+29
-16
lines changed

src/pages/generate.tsx

Lines changed: 29 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -81,17 +81,23 @@ export default function ClientIdentifierGenerator() {
8181
initialStates: ReturnType<typeof getEmptyFormState>;
8282
} = () => {
8383
// Load state from session store, if present, else use empty values.
84-
const storedFormValues = sessionStorage.getItem("formValues");
85-
const formValidationState = sessionStorage.getItem("formValidationState");
86-
const initialValues = storedFormValues
87-
? JSON.parse(storedFormValues)
88-
: initialFormValues;
89-
const initialStates =
90-
formValidationState && storedFormValues
91-
? JSON.parse(formValidationState)
92-
: getEmptyFormState();
93-
94-
return { initialValues, initialStates };
84+
const formStateString = sessionStorage.getItem("formState") || "";
85+
try {
86+
const formState = JSON.parse(formStateString);
87+
// Only restore form data younger than an hour.
88+
if (new Date(formState.timestamp) > new Date(Date.now() - 3600)) {
89+
return {
90+
initialValues: formState.values,
91+
initialStates: formState.states,
92+
};
93+
}
94+
} catch (error) {
95+
// We just return the default values.
96+
}
97+
return {
98+
initialValues: initialFormValues,
99+
initialStates: getEmptyFormState(),
100+
};
95101
};
96102

97103
/** Create a modified formik instance supporting verbose field states. */
@@ -214,11 +220,18 @@ export default function ClientIdentifierGenerator() {
214220
}
215221

216222
// Save state of the form.
217-
sessionStorage.setItem("formValues", JSON.stringify(formik.values));
218-
sessionStorage.setItem(
219-
"formValidationState",
220-
JSON.stringify(formik.states.all)
221-
);
223+
try {
224+
sessionStorage.setItem(
225+
"formState",
226+
JSON.stringify({
227+
values: formik.values,
228+
states: formik.states.all,
229+
timestamp: new Date(),
230+
})
231+
);
232+
} catch (exception) {
233+
// Failing to save form state is no drama..
234+
}
222235
};
223236

224237
/** Set field validation status for each field.

0 commit comments

Comments
 (0)