skip to Main Content

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


  1. The form values that you’re getting from the formik library are made non-extensible. When you do const 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.

    Login or Signup to reply.
  2. Maybe you should declare the object prepareBody in a different way?

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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search