英文:
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 'message' does not exist on type '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>
)}
答案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 'message' does not exist on type 'MyErrorResponse'.
It's a typescript error that indicates you have invalid type.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论