簡體   English   中英

react-hook-form 處理 handleSubmit 中的服務器端錯誤

[英]react-hook-form handling server-side errors in handleSubmit

我很難弄清楚如何處理不一定與react-hook-form的單個輸入字段有關的錯誤。 handleSubmit ,我如何處理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>
  )
}

是否有一種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."
                }
            ]
        }
    ]
}

為了將錯誤從服務器顯示給您的用戶,您需要使用:

  • setError在服務器返回錯誤響應時以編程方式設置錯誤。
  • errors以獲取表單中每個字段的錯誤狀態以顯示給用戶。
const { setError, errors } = useForm<LoginFormData>();

在您的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',
      });
    }
  });

在您的組件中

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

現場演示

編輯 64469861/react-hook-form-handling-errors-in-handlesubmit

受到@NearHuscarl 的回答的啟發,我在usernamepassword輸入中進行了以下 hack st 更改將消除單個錯誤。

如果您的錯誤與表單中的多個字段相關,則此 hack 不能很好地擴展,但它適用於登錄用例。

提交時:

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

    const [err, userLoginResult] = await to<AxiosResponse>(axios.post(url, data)) // see await-to-js 
    if (userLoginResult) {
      alert('Login successful')
    }
    else if (err) {
      const formError = { type: "server", message: "Username or Password Incorrect" }
      // set same error in both:
      setError('password', formError)
      setError('username', formError)
    }
  })

成分:

  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>
        <div>{errors.username && errors.password?.message /*note the cross check*/}</div>
        <button type="submit"> </button>
      </form>
    </div>
  )

通過在errors.passworderrors.username上設置和呈現錯誤,當用戶更新這些字段中的任何一個時,錯誤就會消失。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM