Search code examples
javascriptreact-final-form

How to update a form with error data after unsuccessful submit?


I am using react-final-form.

<Form
  onSubmit={
    (values) => makeAPICall(values).catch(e => ????)
  }
>
...
  <Field name='name'>
    ...
  </Filed>
...
</Form>

Lets say that the error that comes back is about the name not being unique.

I would like to set the error on the Field based on message from the e.

I can't figure out the way how to modify the form state from inside a catch.


Solution

  • The react-final-form project has a codesandbox about submission error handling.
    It's here: https://codesandbox.io/s/9y9om95lyp

    Basically in your Forms render prop, you have to pass it a destructured object containing submitError and check for the presence of a submit error in your field.

    <Form
      onSubmit={values => makeAPICall(values).catch(e => return { username: e })}
      // ...
      render={({
        handleSubmit,
        values,
        // ...
       }) => (
        <form onSubmit={handleSubmit}>
          <Field name="username">
            {({ input, meta }) => (
              <div>
                <label>Username</label>
                <input {...input} type="text" placeholder="Username" />
                {meta.submitError && meta.touched && <span>{meta.submitError}</span>}
              </div>
            )}
          </Field>
        </form>
       )}
    />