Unable to add property identity: The object cannot be extended
P粉338969567
P粉338969567 2023-09-19 13:41:04
0
2
548

When I tried to prepare my POST request body, I encountered a simple TypeError.

This is my handleSubmit function:

const handleSubmit = (values: any, formikHelpers: FormikHelpers<any>) => {
    const prepareBody = { ...values.customerCase};
    if (type === '1') {
      console.log(prepareBody);
      prepareBody.case.identity= {}; // 即使我删除这一行也会出错
      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 questions but didn't find the correct answer. Do you have any ideas? Thanks

P粉338969567
P粉338969567

reply all(2)
P粉052724364

Maybe you should declare the prepareBody object differently?

const prepareBody ={
case: {
    identity: {
        title: null,
        firstName: null,
        lastName: null
    },
    type: null
},
...values.customerCase

}

And don't forget to check the properties in the object:

values?.customerCase?.customer?.contact?.title

Or use destructuring:

const {
customerCase: {
    customer: {
        contact: {
            title,
            firstName,
            lastName
        }
    }
}

} = values ​​|| {};

P粉436410586

The form values ​​you get from the formik library are non-extensible. When you do const prepareBody = { ...values.customerCase}; you create an object that contains a copy of all original values, but for non-original values ​​(such as object) is added, that's why you can't extend it.

To be able to modify it, you need to create a deep copy of values.customerCase. Now, the Javascript standard provides the structuredClone method to help you achieve this.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!