Home  >  Q&A  >  body text

Unable to add property identity: The object cannot be extended

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粉338969567P粉338969567417 days ago637

reply all(2)I'll reply

  • P粉052724364

    P粉0527243642023-09-20 00:51:29

    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 ​​|| {};

    reply
    0
  • P粉436410586

    P粉4364105862023-09-20 00:05:29

    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.

    reply
    0
  • Cancelreply