jaredpalmer / formik

Build forms in React, without the tears 😭
https://formik.org
Apache License 2.0
33.71k stars 2.77k forks source link

Empty form errors immediatyely after validateForm() #3875

Closed v1valasvegan closed 9 months ago

v1valasvegan commented 10 months ago

Bug report

Form errors object doesn't get updated after running validateForm, looks like it updates asynchronously and I can't access it where needed inside handler.

Current Behavior

Leave the First Name empty and click Va li date, you'll see an alert with empty errors . errors are undefined after running validateForm, they get updated eventually, but I can't access them right after validation.

Expected behavior

errors are set after validation, the alert shows errors

Reproducible example

import React from "react";
import ReactDOM from "react-dom";
import { Formik, Field, Form } from "formik";
import * as yup from "yup";

const Schema = yup.object({
  firstName: yup.string().required()
});

const Basic = () => (
  <div>
    <h1>Sign Up</h1>
    <Formik
      validationSchema={Schema}
      initialValues={{
        firstName: "",
        lastName: "",
        email: ""
      }}
      onSubmit={async (values) => {
        await new Promise((r) => setTimeout(r, 500));
        alert(JSON.stringify(values, null, 2));
      }}
    >
      {({ validateForm, errors }) => (
        <>
          <Form>
            <label htmlFor="firstName">First Name</label>
            <Field id="firstName" name="firstName" placeholder="Jane" />

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

            <label htmlFor="email">Email</label>
            <Field
              id="email"
              name="email"
              placeholder="jane@acme.com"
              type="email"
            />
            <button type="submit">Submit</button>
          </Form>
          <pre>{JSON.stringify(errors, null, 2)}</pre>
          <button
            onClick={async () => {
              await validateForm();
              alert(JSON.stringify(errors));
              // do my stuff depending on whether validation failed
            }}
          >
            Va li date
          </button>
        </>
      )}
    </Formik>
  </div>
);

ReactDOM.render(<Basic />, document.getElementById("root"));

https://codesandbox.io/s/charming-wave-g8tgz3?file=/index.js

Suggested solution(s)

Maybe there's a workaround to access the errors after validation? I need to know if validation failed inside my handler function.

Additional context

I use validatilnSchema and yup to run validation.

myNameIsDu commented 9 months ago

validateForm will return errors object, just change into this

const errors = await validateForm();
alert(errors)