Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async/Await with Formik?

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>
like image 259
chobo2 Avatar asked Mar 07 '19 22:03

chobo2


1 Answers

Is something like this what you're looking for?

onSubmit={ async (values, { setSubmitting }) => {
    await ...
    setSubmitting(false)
}}
like image 138
Alexander Avatar answered Sep 28 '22 06:09

Alexander