最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - AsyncAwait with Formik? - Stack Overflow

programmeradmin1浏览0评论

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>

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>
Share Improve this question asked Mar 7, 2019 at 22:49 chobo2chobo2 85.8k207 gold badges551 silver badges861 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 10

Is something like this what you're looking for?

onSubmit={ async (values, { setSubmitting }) => {
    await ...
    setSubmitting(false)
}}

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

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


onSubmit={(values, { setSubmitting }) => {
    _handleSubmit(values)
    setSubmitting(false)
}}

This has been supported out of the box since late 2020. See this Github issue which links to this runnable example:

import React from 'react';
import ReactDOM from 'react-dom';
import { Formik, Field, Form } from 'formik';

const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

const Example = () => (
  <div>
    <h1>Sign Up</h1>
    <Formik
      initialValues={{
        firstName: '',
        lastName: '',
        email: '',
      }}
      onSubmit={async (values) => {
        await sleep(500);
        alert(JSON.stringify(values, null, 2));
      }}
    >
      {({ isSubmitting }) => (
        <Form>
          <label htmlFor="firstName">First Name</label>
          <Field name="firstName" placeholder="Jane" />

          <label htmlFor="lastName">Last Name</label>
          <Field name="lastName" placeholder="Doe" />

          <label htmlFor="email">Email</label>
          <Field name="email" placeholder="[email protected]" type="email" />

          <button type="submit" disabled={isSubmitting}>
            Submit
          </button>
        </Form>
      )}
    </Formik>
  </div>
);

ReactDOM.render(<Example />, document.getElementById('root'));

I personally wound up here because I was calling await on a function that I didn't notice wasn't returning a promise. Something like

onSubmit={
    async (values) => {
        await someFunction();
        console.log('done');
    }
}

//...

someFunction() {
    fetch('http://example.'); // d'oh! missing a return statement!
}
发布评论

评论列表(0)

  1. 暂无评论