Source:  Twitter logo

I am using formik and I am wondering how to use async/await with onSubmit

<Formik
  initialValues={{ email: '' }}
  onSubmit={(values, { setSubmitting }) => {
    // how to do async/await here.
  }}
  validationSchema={Yup.object().shape({
    email: Yup.string()
      .email()
      .required('Required'),
  })}
>
  {props => {
    const {
      values,
      touched,
      errors,
      dirty,
      isSubmitting,
      handleChange,
      handleBlur,
      handleSubmit,
      handleReset,
    } = props;
    return (
      <form onSubmit={handleSubmit}>
        <label htmlFor="email" style={{ display: 'block' }}>
          Email
        </label>
        <input
          id="email"
          placeholder="Enter your email"
          type="text"
          value={values.email}
          onChange={handleChange}
          onBlur={handleBlur}
          className={
            errors.email && touched.email ? 'text-input error' : 'text-input'
          }
        />
        {errors.email &&
          touched.email && <div className="input-feedback">{errors.email}</div>}

        <button
          type="button"
          className="outline"
          onClick={handleReset}
          disabled={!dirty || isSubmitting}
        >
          Reset
        </button>
        <button type="submit" disabled={isSubmitting}>
          Submit
        </button>

        <DisplayFormikState {...props} />
      </form>
    );
  }}
</Formik>

Is something like this what you're looking for?

onSubmit={ async (values, { setSubmitting }) => {
    await ...
    setSubmitting(false)
}}
9 users liked answer #0dislike answer #09
Alexander profile pic
Alexander

As alternative, you could make an seperate function as well.

async function _handleSubmit(values) {
   await...
}


onSubmit={(values, { setSubmitting }) => {
    _handleSubmit(values)
    setSubmitting(false)
}}
2 users liked answer #1dislike answer #12
louisrtz profile pic
louisrtz

Copyright © 2022 QueryThreads

All content on Query Threads is licensed under the Creative Commons Attribution-ShareAlike 3.0 license (CC BY-SA 3.0).