Handling errors with React and Formik

Viewed 1551

I'm trying to get errors directly inside Formik and log the errors on the console but t it's not working.

  1. Submit function
const submitForms = (errors) => {
    console.log("ERRORS ON SUBMIT", errors);
    handleNext();
  };
  1. Attempt to catch errors inside Formik
<Formik
  initialValues={{ ...initialValues }}
  validationSchema={kycFormSchema}
  onSubmit={({errors}) => submitForms(errors)}
 />

I'm actually using Yup to validate the form but I also want to catch the errors and pass them in submitForms function. Am I missing something?

Thanks in advance.

2 Answers

Seems like according to the official documentation onSubmit() function of the Formik library doesn't de-structure any error props.

You can find the list of available props within onSubmit() at the following link : FORMIK | onSubmit( )

This is the functidefinition of the onSubmit() function :

  • onSubmit: (values: Values, formikBag: FormikBag) => void | Promise

If the form doesn't pass validationSchema, onSubmit will not call. It only call when don't have errors. onSubmit only have params are values and FormikBag.

Note: errors, touched, status and all event handlers are NOT included in the FormikBag.

You can use errors is a props of a Child Component: https://formik.org/docs/api/formik#component-reactcomponenttypeformikpropsvalues

<Formik component={ContactForm} />;
 
 const ContactForm = ({
   handleSubmit,
   handleChange,
   handleBlur,
   values,
   errors,
 }) => (
   <form onSubmit={handleSubmit}>
     <input
       type="text"
       onChange={handleChange}
       onBlur={handleBlur}
       value={values.name}
       name="name"
     />
     {errors.name && <div>{errors.name}</div>}
     <button type="submit">Submit</button>
   </form>
 );
Related