我有什么
我使用useQuery
的onSuccess
回调来验证API调用是否返回数据,如果响应不返回数据,则提示"没有找到结果";呈现。
toast为每个观察者呈现多次,我知道这是预期的行为,因为钩子是为每个观察者执行的。
我想要的
我搜索了一些资源,尽管其中一些提到可以使用全局回调来避免这种行为,但我不清楚如何过滤请求以仅为其中一些请求显示此toast。我的意思是,如果请求的查询键等于&;search&;并且响应没有返回结果。
const queryClient = new QueryClient({
queryCache: new QueryCache({
onSuccess: (error) =>
// how to filter here the request to show the toast
// according to the queryKey and if no data is retrieved from the backend
}),
})
其他问题
- 还有其他方法来避免这种行为(在每个观察者运行代码)?
更新1
我使用axios作为客户端,我应该如何处理TS输入错误或成功回调?
问题是您得到了一个伪装成SUCCESS条件的FAIL条件。比如你的api返回一个200响应,但没有数据…在这种情况下,正确的做法不是用onSuccess处理程序来处理问题,而是从查询函数抛出一个错误,让onError处理程序来管理它。例如
useQuery({
queryKey,
queryFn: async (..args) => {
const response = await actualQueryFn(...args);
if(!response.data) throw new Error("No Data");
return response;
}
});
onError处理程序将接收错误和查询。从那里,您可以内省查询以确定要显示的消息。
。
const queryClient = new QueryClient({
queryCache: new QueryCache({
onError: (error, query) => {
// Do stuff with query and error to show the right toast message.
}
}),
})