react-hook-form 处理 handleSubmit 中的服务器端错误

joe*_*uch 9 typescript reactjs react-hook-form

我很难弄清楚如何处理不一定与react-hook-form. 换句话说,我如何处理handleSubmit错误?

例如,具有以下形式:

import to from 'await-to-js'
import axios, { AxiosResponse } from 'axios'
import React from "react"
import { useForm } from "react-hook-form"

type LoginFormData = {
  username: string,
  password: string,
}

export const Login: React.FC = () => {
  const { register, handleSubmit } = useForm<LoginFormData>()

  const onSubmit = handleSubmit(async (data) => {
    const url = '/auth/local'

    const [err, userLoginResult] = await to<AxiosResponse>(axios.post(url, data))
    if (userLoginResult) {
      alert('Login successful')
    }
    else if (err) {
      alert('Bad username or password')
    }
  })

  return (
    <div className="RegisterOrLogIn">
      <form onSubmit={onSubmit}>
        <div>
          <label htmlFor="username">username</label>
          <input name="username" id="username" ref={register} />
        </div>
        <div>
          <label htmlFor="password">Password</label>
          <input type="password" id="password" name="password" ref={register} />
        </div>
        <button type="submit"> </button>
      </form>
    </div>
  )
}
Run Code Online (Sandbox Code Playgroud)

有没有react-hook-form办法通知用户用户名或密码有误? 就像,除了alert()

也许这在其他地方得到了回答,但我找不到。


澄清 从服务器收到的错误与单个字段无关:

{
    "statusCode": 400,
    "error": "Bad Request",
    "message": [
        {
            "messages": [
                {
                    "id": "Auth.form.error.invalid",
                    "message": "Identifier or password invalid."
                }
            ]
        }
    ],
    "data": [
        {
            "messages": [
                {
                    "id": "Auth.form.error.invalid",
                    "message": "Identifier or password invalid."
                }
            ]
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

Nea*_*arl 9

为了将错误从服务器显示给您的用户,您需要使用:

  • setError 当服务器返回错误响应时以编程方式设置错误。
  • errors 获取表单中每个字段的错误状态以显示给用户。
const { setError, errors } = useForm<LoginFormData>();
Run Code Online (Sandbox Code Playgroud)

在你的handleSubmit回调中

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',
      });
    }
  });
Run Code Online (Sandbox Code Playgroud)

在您的组件中

<label htmlFor="username">username</label>
<input name="username" id="username" ref={register} />
<div>{errors.username && errors.username.message}</div>
Run Code Online (Sandbox Code Playgroud)

现场演示

编辑 64469861/react-hook-form-handling-errors-in-handlesubmit

  • 这仅处理用户名或密码错误的情况,但 api 超时错误怎么办 (2认同)