react-hook-form handling server-side errors in handleSubmit

In order to display the error from the server to your user, you need to use:

  • setError to set the error programmatically when the server returns an error response.
  • errors to get the error state of every fields in your form to display to the user.
type FormInputs = {
  username: string;
};

const { setError, formState: { errors } } = useForm<FormInputs>();

In your handleSubmit callback

axios
  .post(url, data)
  .then((response) => {
    alert("Login successful");
  })
  .catch((e) => {
    const errors = e.response.data;

    if (errors.username) {
      setError('username', {
        type: "server",
        message: 'Something went wrong with username',
      });
    }
    if (errors.password) {
      setError('password', {
        type: "server",
        message: 'Something went wrong with password',
      });
    }
  });

In your component

<label htmlFor="username">username</label>
<input id="username" {...register("username")} />
<div>{errors.username && errors.username.message}</div>

Live Demo

Edit 64469861/react-hook-form-handling-errors-in-handlesubmit

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)