Formik - React - How to get out of the onSubmit

Viewed 19

I'm using Formik in my React app.

In my onSubmit, I'm making a API call to a service, if that fails I'd like the rest of the onSubmit to stop right there and do nothing else - how can I implement such a break?

e.g.

const formik = useFormik({
    initialValues: { name: '' },
    validationSchema: mySchema,
    onSubmit: async (values) => {
        setIsSubmitting(true);

        let details = await axios.get(`${process.env.MY_API}/release/${values.number}`)
                                 .catch(//Don't go any further)

   

I tried rejecting the promise, return and break but nothing seems to work.

Any ideas?

Thanks.

1 Answers

Use async/await or then/catch.

Then/Catch:

axios.get().then(() => /* Submitting */).catch(() => /* Error */)

Async/Await:

try {
  const result = await axios.get();
  if (result?.success === true) {  // Based on what the API returns
    /* Submitting */
  } else {
    /* Error */
  }
} catch (errorMessage) {

}

Related