Search code examples
reactjsvalidationnext.jsformikyup

How to use useFormik hook with async await in onSubmit event?


I'm trying to find how to use async-await with useFormik hooks in onSubmit event. I want to use axios library inside onSubmit event but with async await, but I'm not able to find the way how to use async await inside onSubmit event.

import React from 'react';
import { useFormik } from 'formik';

const SignupForm = () => {
  const formik = useFormik({
    initialValues: {
      firstName: '',
      lastName: '',
      email: '',
    },
    onSubmit: values => {
      alert(JSON.stringify(values, null, 2));
    },
  });
  return (
    <form onSubmit={formik.handleSubmit}>
      <label htmlFor="firstName">First Name</label>
      <input
        id="firstName"
        name="firstName"
        type="text"
        onChange={formik.handleChange}
        value={formik.values.firstName}
      />
      <label htmlFor="lastName">Last Name</label>
      <input
        id="lastName"
        name="lastName"
        type="text"
        onChange={formik.handleChange}
        value={formik.values.lastName}
      />
      <label htmlFor="email">Email Address</label>
      <input
        id="email"
        name="email"
        type="email"
        onChange={formik.handleChange}
        value={formik.values.email}
      />
      <button type="submit">Submit</button>
    </form>
  );
};

Solution

  • The onSubmit event receives a callback function, it can be a normal function or async function:

    ...
    onSubmit: async (values) => {
      // await something here...
    },
    ...