如何设置错误消息从Axios响应与Typescript和Next.js?

p8ekf7hl  于 2022-11-18  发布在  TypeScript
关注(0)|答案(1)|浏览(240)

我有一个Next.js应用程序,它为注册表单调用API。当服务器端出现验证错误时,我会得到如下响应:

{"message":"The given data was invalid.","errors":{"email":["The email has already been taken."],"password":["The password must be at least 8 characters."]}}

在我的代码中,我希望向用户显示emailpassword错误(如果它们存在的话)。目前我的代码是:

const RegisterPage: NextPageWithLayout = () => {

  const [isSubmitting, setIsSubmitting] = useState<boolean>(false);
  const [setEmailError, emailError] = useState<string | null>(null)
  const [setPasswordError, passwordError] = useState<string | null>(null)

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    if (isSubmitting) return;
    setIsSubmitting(true);
    try {
      // handle success
    } catch (err){
      // @ts-ignore
      const errors = err?.response?.data?.errors;
      if(errors instanceof Object){
        setEmailError(errors['email']) // this does not work
        setPasswordError(errors['password'] || null) // this does not work
      }

      setIsSubmitting(false);
    }
  };

然而,这段代码不起作用。我的IDE在设置电子邮件和密码错误的行上显示了几个错误:

TS2349: This expression is not callable.   
   Type 'String' has no call signatures.
TS2721: Cannot invoke an object which is possibly 'null'.

如何设置emailErrorpasswordError变量,以便在出现错误消息时向用户显示错误消息?

nvbavucw

nvbavucw1#

useState中,Setter方法是第二个参数,而不是第一个参数。

const [emailError, setEmailError  ] = useState<string | null>(null)
const [passwordError, setPasswordError] = useState<string | null>(null)

将类型添加到错误并检查错误是否为空

const errors: {email?: string, password?: string} = err?.response?.data?.errors;
  if(errors){
    setEmailError(errors?.email || null)  
    setPasswordError(errors?.password || null)  
  }

相关问题