I’m facing a simple TypeError when I try to prepare my POST body.
Here is my handleSubmit function :
const handleSubmit = (values: any, formikHelpers: FormikHelpers<any>) => {
const prepareBody = { ...values.customerCase};
if (type === '1') {
console.log(prepareBody);
prepareBody.case.identity= {}; // error here even if I remove this line
prepareBody.case.identity.title =
values.customerCase.customer.contact.title;
prepareBody.case.identity.firstName =
values.customerCase.customer.contact.firstName;
prepareBody.case.identity.lastName =
values.customerCase.customer.contact.lastName ;
prepareBody.case.type = type;
}
PostCustomer({
reference: props.reference,
body: prepareBody,
})
.unwrap()
.then(() => {
formikHelpers.resetForm();
history.push('/success');
})
.catch(() => alertToasts('error', t('toast.error')));
};
I saw many similar issues but didn’t find the right answer.
Do you have an idea ?
Thanks
2
Answers
The form values that you’re getting from the
formik
library are made non-extensible. When you doconst prepareBody = { ...values.customerCase};
you create an object where a copy of all the primitives, however, a reference to non-primitives (like an object) is added, which is why you’re not able to extend it.To be able to modify it, you’ll instead need to create a deep copy of
values.customerCase
. Javascript standard now provides structuredClone method that’ll help you do this.Maybe you should declare the object prepareBody in a different way?
}
and don’t forget to check the properties in the object:
or use destructuring:
} = values || {};