Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formik onSubmit function is not working on my code

I am creating a form by using react and formik.Below is my code:

<div>
  <Formik
    initialValues={{
      email: ""
    }}
    onSubmit={(values: FState, setSubmitting: any) => {
      console.log("Enter in submit function", values);
      setTimeout(() => {
        alert(JSON.stringify(values, null, 2));
        setSubmitting(false);
      }, 500);
    }}
    validationSchema={validationSchemaGlobal}
  >
    {({
      errors,
      touched,
      handleBlur,
      handleChange,
      isSubmitting,
      values,
      handleSubmit
    }: any) => (
      <div>
        <Cards>
          <form onSubmit={handleSubmit}>
            <CardBody>
              <h4>
                Enter Your Email Address and we'll send you a link to reset your
                password
              </h4>
              <Field
                type="text"
                id="email"
                value={values.email}
                component={CustomInput}
                onChange={handleChange}
                onBlur={handleBlur}
              />
              {errors.email && touched.email ? (
                <div style={{ color: "red" }}>{errors.email}</div>
              ) : null}
            </CardBody>
            <CardFooter>
              <br />
              <button type="submit" disabled={isSubmitting}>
                Send Password Reset Link
                {/* {isSubmitting && <i className="fa fa-sponner fa-spin"/>} */}
              </button>
            </CardFooter>
          </form>
        </Cards>
      </div>
    )}
  </Formik>
</div>

In this formik form, onSubmit function not working. I dont know why? Please tell me guys what is problem with my code?

like image 886
NewCoder Avatar asked Mar 19 '19 09:03

NewCoder


People also ask

What is dirty Formik?

Returns true if values are not deeply equal from initial values, false otherwise. dirty is a readonly computed property and should not be mutated directly.

Why does Formik touch all fields before submit?

Why does Formik touch all fields before submit? It is common practice to only show an input's errors in the UI if it has been visited (a.k.a "touched"). Before submitting a form, Formik touches all fields so that all errors that may have been hidden will now be visible.

Why is onsubmit not working?

In my case, onSubmit was not working because I forgot to wrap my form in the <form></form> tag. A stupid issue, but it can be the reason for this behavior. If the above solutions don't work, check that you have the form tag.

Why can't I get handlesubmit to work with my form?

You're missing an inner <form> element and handleSubmit should be attached to that form element, not the submit button. Sorry, something went wrong. Found the issue. onSubmit will be called if the form is valid.

How to trigger onsubmit from an empty object?

Replace that prop with validator= { () => ( {})} i.e. just an empty object being returned. That should pass validation and trigger your onSubmit. You can restore your functionality from there. Show activity on this post.


2 Answers

Check your validationSchema. I ran into this problem and found that my validator was returning something that signaled to Formik the form was invalid, but no other warnings or messages were coming up. It just wouldn't submit.

Replace that prop with validator={() => ({})} i.e. just an empty object being returned. That should pass validation and trigger your onSubmit. You can restore your functionality from there.

  <Formik
    initialValues={{
      email: ""
    }}
    onSubmit={() => { console.log("submit!"); }}
    validator={() => ({})}
  >
    {/* */}
  </Formik>
like image 57
Chris Avatar answered Oct 17 '22 20:10

Chris


In my case I use Yup as validator and I accidentally had firstName and lastName in my validationSchema as required but I did not have those values in my form.

My validationSchema was,

const SignupSchema = Yup.object().shape({
  firstName: Yup.string()
    .min(2, 'Too Short!')
    .max(50, 'Too Long!')
    .required('Required'),
  lastName: Yup.string()
    .min(2, 'Too Short!')
    .max(50, 'Too Long!')
    .required('Required'),
  email: Yup.string()
    .email('Invalid email')
    .required('Required'),
  password: Yup.string()
    .min(6, 'Password must be at least 6 characters')
    .max(24, 'Password can be maximum 24 characters')
    .required('Required')
}) 

I just deleted firstName and lastName,

const SignupSchema = Yup.object().shape({
  email: Yup.string()
    .email('Invalid email')
    .required('Required'),
  password: Yup.string()
    .min(6, 'Password must be at least 6 characters')
    .max(24, 'Password can be maximum 24 characters')
    .required('Required')
})

So check your validationSchema and see if you require something that does not exist in your form.

like image 37
Hasan Sefa Ozalp Avatar answered Oct 17 '22 19:10

Hasan Sefa Ozalp