Axios错误响应使用TypeScript、React和React-Query

huangapple go评论58阅读模式
英文:

Axios Error Response Using TypeScript, React and React-Query

问题

我需要显示错误消息,如果没有错误消息,就将其默认为错误状态代码。问题是,它显示属性'message'在类型'MyErrorResponse'上不存在。

auth service

import { AxiosError } from 'axios';
import { useMutation } from 'react-query';
import { _axios, URL_TEMPLATES } from '../api';

export type LoginPayload = {
  username: string;
  password: string;
};

type LoginResponse = {
  data: {
    username: string;
    email: string;
    token: string;
  };
};

type MyErrorResponse = {
  errors: { detail: string }[];
};

export const useLogin = () => {
  return useMutation<LoginResponse, AxiosError<MyErrorResponse>, LoginPayload>(
    (payload) => _axios.post(URL_TEMPLATES.LOGIN, { ...payload })
  );
}

component

const { mutate, error } = useLogin();

{error && (
  <Typography variant='h6' sx={{ color: theme.palette.red, mt: 2 }}>
    {error.response?.data.message}
  </Typography>
)}
英文:

I need to display the error message and if it has no error message just default it to an error status code. Problem right now is that it says Property &#39;message&#39; does not exist on type &#39;MyErrorResponse&#39;.

Axios错误响应使用TypeScript、React和React-Query

auth service

import { AxiosError } from &#39;axios&#39;
import { useMutation } from &#39;react-query&#39;
import { _axios, URL_TEMPLATES } from &#39;../api&#39;

export type LoginPayload = {
  username: string;
  password: string;
};

type LoginResponse = {
  data: {
    username: string;
    email: string;
    token: string;
  };
};

type MyErrorResponse = {
  errors: { detail: string }[];
};

export const useLogin = () =&gt; {
  return useMutation&lt;LoginResponse, AxiosError&lt;MyErrorResponse&gt;, LoginPayload&gt;(
    (payload) =&gt; _axios.post(URL_TEMPLATES.LOGIN, { ...payload })
  )
}

component

const { mutate, error } = useLogin()

      {error &amp;&amp; (
        &lt;Typography variant=&#39;h6&#39; sx={{ color: theme.palette.red, mt: 2 }}&gt;
          {error.response?.data.message}
        &lt;/Typography&gt;
      )}

答案1

得分: 0

你的 `MyErrorResponse` 应根据后端返回的内容进行类型定义。在这种情况下,它应该是这样的,

```typescript
type MyErrorResponse = {
  message: string
};

这个提示来自你得到的错误,Property 'message' does not exist on type 'MyErrorResponse'。这是一个 TypeScript 错误,表明你的类型定义是无效的。


<details>
<summary>英文:</summary>

Your `MyErrorResponse` should be typed according what you return from the backend. In this case, it should be, 

```typescript
type MyErrorResponse = {
  message: string
};

the hint is from the error you got, Property &#39;message&#39; does not exist on type &#39;MyErrorResponse&#39;. It's a typescript error that indicates you have invalid type.

huangapple
  • 本文由 发表于 2023年2月19日 18:45:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/75499562.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定