final-form / react-final-form

🏁 High performance subscription-based form state management for React
https://final-form.org/react
MIT License
7.39k stars 481 forks source link

handleSubmit throws error if field validations fails #773

Open hariskhan10 opened 4 years ago

hariskhan10 commented 4 years ago

Are you submitting a bug report or a feature request?

I am submitting an issue; while I am using a promise for resetting the fields on submit, if there is no field validation error and I submit the form; its working fine; but if I submit the form while validation error exists, it throws the error of .then is undefined. I am using Promise to reset the form fields once form submitted successfully.

I tried to search in your examples form but didn't find any example where its a validation + form resetting.

What is the current behavior?

https://codesandbox.io/s/react-final-form-reset-validation-jbpcc

What is the expected behavior?

Ideally, it should not go to the submit form until all the validation error is not solved.

Sandbox Link

What's your environment?

Other information

Hyperkid123 commented 4 years ago

@hariskhan10 the handleSubmit form callback does not return anything because the prosmise was not even called. HandleSubmit is called always and actually validates the form and only fi the form is valid it triggers the onSubmit callback. If you want to react on the submit function you have to do it inside the onSubmit callback. Like this:

    <div className="App">
      <Form
        initialValues={{
          cinemaName: "",
          cinemaAddress: ""
        }}
        validate={values => {
          const errors = {};
          if (!values.cinemaName) {
            errors.cinemaName = "Required";
          }
          if (!values.cinemaAddress) {
            errors.cinemaAddress = "Required";
          }

          return errors;
        }}
        onSubmit={(values, formApi) =>
          onSubmit(values).then(() => {
            setTimeout(formApi.reset);
          })
        }
        render={({ handleSubmit, submitting, pristine }) => (
          <form id="myform" onSubmit={handleSubmit}>...</form>
    />
  </div>
allens01 commented 3 years ago

I had a similar problem and this fix worked for me!