'How can I handle error of array of objects with useformik, yup and material ui?

I have a form witch contains input as "firstName, lastName" etc. When the user submit it the data will be send to the server with the following body

    employee: [
      {
        key: "property",
        key: "property",
      },
    ],
    manager: [
      {
        key: "property",
        key: "property",
      },
    ],
    customer: [
      {
        name: "John",
      },
      {
        name: "Doe",
      },
    ]

Everything works fine, but I'm trying to improve my code for one of the input.

Basically to submit the form with success the user must enter at least one customer name in the "customer input" and then press the button "add customer". After that I clean the input and render a list of "chip" with customer's name. The user can add as many customers as he wants.

Because I don't know how to handle a array of objects with useFormik, I did handle it myself with the following code:

  const [customersList, setCustomersList] = useState<Array<Customer>>([]);
  const [displayError, setDisplayError] = useState<Boolean>(false);
  const [errorMessage, setErrorMessage] = useState<string>('');


  const updateCustomerList = () => {
    let customerName = capitalizeWords(formik.values.customer_name);

    if (customerName.length === 0) {
      setErrorMessage('Customer name is required');
      return setDisplayError(true);
    }

    setCustomersList([...customersList, { name: customerName }]);

    formik.setFieldValue('customer_name', '');
  };

  const isDuplicateCustomer = () => {
    let customerName = capitalizeWords(formik.values.customer_name);

    const isDuplicate = customersList.some(
      (customer) => customer.name === customerName,
    );

    if (isDuplicate == true) {
      setErrorMessage('Duplicate');
      setDisplayError(true);
      formik.setFieldValue('customer_name', '');
      return true;
    }
    return false;
  };

  const onAddButtonClick = () => {
    if (!isDuplicateCustomer()) {
      updateCustomerList();
    }
  };

But now it's hard to handle errors on the customer's input with useFormik and yup, because I defined the "customer" input as string, and because I clean the input each time the user press the button 'add' it can't work.

My question is: is it possible to handle the "customersList" with useFormik or formik and get ride on "updateCustomerList" and "isDuplicateCustomer" by using native function of formik and yup validation ?

Because now the only way I found to submit the form is to handle the error myself and make the customer's input not required with yup.

Here is a codesandbox: https://codesandbox.io/s/quiet-tree-f26mte?file=/src/App.js



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source