Skip to content

Commit

Permalink
[GEN-1848]: fix form deep values (#1901)
Browse files Browse the repository at this point in the history
  • Loading branch information
BenElferink authored Dec 2, 2024
1 parent cf9e48f commit a9f1d05
Showing 1 changed file with 9 additions and 2 deletions.
11 changes: 9 additions & 2 deletions frontend/webapp/hooks/common/useGenericForm.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,14 @@
import { useState } from 'react';

export const useGenericForm = <Form = Record<string, any>>(initialFormData: Form) => {
const [formData, setFormData] = useState<Form>({ ...initialFormData });
function copyInitial() {
// this is to avoid reference issues with the initial form data,
// when an object has arrays or objects as part of it's values, a simple spread operator won't work, the children would act as references,
// so we use JSON.parse(JSON.stringify()) to create a deep copy of the object without affecting the original
return JSON.parse(JSON.stringify(initialFormData));
}

const [formData, setFormData] = useState<Form>(copyInitial());
const [formErrors, setFormErrors] = useState<Partial<Record<keyof Form, string>>>({});

const handleFormChange = (key?: keyof typeof formData, val?: any, obj?: typeof formData) => {
Expand Down Expand Up @@ -30,7 +37,7 @@ export const useGenericForm = <Form = Record<string, any>>(initialFormData: Form
};

const resetFormData = () => {
setFormData({ ...initialFormData });
setFormData(copyInitial());
setFormErrors({});
};

Expand Down

0 comments on commit a9f1d05

Please sign in to comment.