jaredpalmer / formik

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

Ability to detect aborted form submissions due to validation errors. #2109

Open slorber opened 4 years ago

slorber commented 4 years ago

🚀 Feature request

Current Behavior

When calling form.submitForm() it throws if:

Desired Behavior

Keep same behavior as current but let user be able to differenciate those different kind of failures with callbacks?

When form.submit() is called, if async validation return errors, I want to be able to emit an error toast/notification/snackbar/whatever

I don't want this toast if it's a validation network error, or if it's the form submission that fails (or if I do I don't want the same message for the toast according to the case)

Suggested Solution

useFormik({
  onSubmitValidationExecutionError: () => { toast("could not validate the form") },
  onSubmitValidationError: () => { toast("your form is invalid") },
  onSubmitExecutionError: () => { toast("your form is valid but it couldn't be submitted for unknown reasons") },
})

Who does this impact? Who is this for?

For people who need fine-grained form submission error handling logic.

Describe alternatives you've considered

Adding some custom field to the error thrown so that I can catch if and emit different toasts according to the failure situation.

Handling this fine-grained error handling in userland (which requires reimplementing submitForm's logic, so not ideal).

jaredpalmer commented 4 years ago

Go for it with PR. We’ll likely debate naming. It I think this makes sense

keithjgrant commented 4 years ago

Something like this would be really helpful. I don't even need the "fine grained" control.

We've had multiple times during development when a form is not submitting and it's a real pain to track down exactly why if our UI is mishandling a field error.

Is there already any sort of onSubmitError handler to hook into?

aminalali8 commented 4 years ago

+1

manugeo commented 3 years ago

+1

johnrom commented 3 years ago

It would be a million times better (in my opinion) to be able to intercept the events dispatched to Formik like { type: 'SUBMIT_FAILED', reason: "VALIDATION_FAILED", errors } or whatever.

const formik = useFormik(...props);

formik.useIntercept(
  React.useCallback(message => {
    if (message.type === "SUBMIT_FAILED") {
      if (message.reason === "VALIDATION_ERROR") {
        toast('something bad happened in validation');
      } else if (message.reason === "VALIDATION_FAILED") {
        toast(`bad inputs, bad. ${JSON.stringify(message.errors)}`);
      } else if (message.reason === "SUBMIT_ERROR") {
        toast('something bad happened in submission');
      }
    }
  }, [])
);

Although ultimately VALIDATION_ERROR and SUBMIT_ERROR should throw instead and the only time we should catch them is using the default submit handler, handleSubmit.