Bartłomiej Sobieszek
Bartłomiej Sobieszek

Reputation: 2800

How do you validate http requests on submit in Formik?

From what I saw the submit event works only with some static checks like Yup or something.

What I actually need is to perform a request like /product/store and if any errors got received from the server then display them on the form.

For logical reasons I cannot make that request in validate method since... its not a submit. I expect submit to make that /product/store request, and if it fails then set error fields.

My assume is that validactionSchema and validate method is only for static checks like regexp matches.

The example in formik docs is misleading since it uses some setTimeout promise which is logicless, but actual request to the server has its meaning and its supposed to be made onSubmit.

No redux btw.

Upvotes: 1

Views: 923

Answers (1)

Jap Mul
Jap Mul

Reputation: 18759

Assuming that the response from your server contains the errors you can set the errors for the fields using the setFieldError function.

The code below assumes that the server returns an error status code with a response that contains the errors in the follow format [{"field":"name","message":"Name cannot be empty."}].

const handleSubmit = (values, actions) => {
  makeSomePostRequest(values)
    .then(response => console.log('success!'))
    .catch(error => {
      /* If your server returns something like a 422 when the
         validation fails it will move to the catch part. Here
         you can use the actions.setFieldError to set the errors
         in your form.
      */
      error.response.data.forEach(error => {
        actions.setFieldError(error.field, error.message)
      })
    })
    .finally(() => actions.setSubmitting(false))
}

Upvotes: 2

Related Questions