我正在做一个React JS项目。我正在使用React查询,https://react-query.tanstack.com/以发出API请求。当API抛出422、400或401等时,我现在在onError回调中从服务器检索响应数据时遇到了一个问题
这是我的突变。
let [ createProductMutation, { data, error } ] = useMutation((payload) => createProduct(payload), {
onMutate: () => {
},
onSuccess: (response) => {
},
onError: (err, variables, snapshotValue) => {
//err is not the response from the server.
}
})
正如您在onError回调中看到的,没有办法从服务器检索响应。
数据和错误(createProductMutation旁边的那个(也不是来自服务器的响应。
我试过用这个。
try {
let response = await createProductMutation(data);
// response from the API is not here too, "response"
} catch (e) {
// response from the API is not here too
}
如何在onError回调中检索响应?
let [ createItem ] = useMutation(payload => createItem(payload), {
onError: (error) => {
console.log(error.response.data);
console.log(error.response.status);
}
})
对我来说,上述解决方案奏效了!在onError
内部,应提供error.response。
要获得响应,需要将错误转换为json,然后等待promise。参见下面的例子;消息";无论您的后端为响应消息返回什么。
onError: async (error, variables, context) => {
const errorObj = error;
const errorObjAsJSON = await errorObj.json();
const { message } = errorObjAsJSON;
console.log(message);
},
很明显,你可以通过进一步浓缩
onError: async (error, variables, context) => {
const errorObj = await error.json();
const { message } = errorObj;
console.log(message);
},
TLDR:确保提供给useQuery的函数返回promise
示例
useQuery('getAllUsersInfo', getAllUsersInfo)
请确保getAllUsersInfo函数正在返回promise。
我遇到了同样的问题,因为我提供给useQuery的函数没有返回promise,所以react query认为请求成功,而实际上它没有通过