如何取消RTK Query请求
我正在使用RTK查询来处理我的请求。但是我在取消请求时遇到问题。
场景是这样的,我有一种模式可以显示一个表格来添加todo,但是当用户想要关闭模式时,请求应取消,如果该请求尚待审理。
const [addTodo, { isLoading }] = useAddTodoMutation();
const onSubmit = async (values: ToDo) => {
try {
await addTodo(values).unwrap();
console.log('Successful')
} catch (error) {
console.log('failed')
}
};
我知道有一个中止
可以取消突变,例如addtodo(values).abort();
,我们可以在useffect
用<<<中使用它。代码> useref 。
是否可以编写一种通用方式或自定义钩子来包装我的所有突变并处理组件被卸载时处理取消请求?
I am using the RTK query to handle my requests. But I have a problem canceling requests.
The scenario is like this, I have a modal to show a form to add a todo but, when users want to close the modal the request should be canceled if it is pending yet.
const [addTodo, { isLoading }] = useAddTodoMutation();
const onSubmit = async (values: ToDo) => {
try {
await addTodo(values).unwrap();
console.log('Successful')
} catch (error) {
console.log('failed')
}
};
I know there is an abort
to cancel mutation like addTodo(values).abort();
and we can use it in useEffect
cleanup with useRef
.
Is it possible to write a general way or a custom hook to wrap all my mutations and handle canceling requests when a component will be unmounted?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这样做几乎没有任何价值。如果您的请求待定,只要您不在前几毫秒内,该请求已经发送到服务器,客户端只是在等待响应。即使您取消该请求并且服务器上的数据可能已经更改,服务器也将继续处理该请求。因此,通常让请求完成,然后使所有缓存数据(通常是通过换取)无效,这些数据可能会因突变而改变。
如果取消请求,则不会发生无效。
也就
There is hardly any value in doing that. If your request is pending, as long as you are not within the first few milliseconds, that request has already been sent to the server and the client is just waiting for the response. The server will keep processing that request even if you cancel it and data on the server is probably already changed. So it usually makes sense to let the request finish and then invalidate all cache data (usually, by refetching) that has potentially been changed by the mutation.
If you cancel the request, invalidation will not happen.
All that said: if you triggered your mutation with
myTriggerFunction()
, you can do您可以使用自定义钩子包装突变:
You can use custom hook to wrap mutation:
假设您将更新用户:
您可以致电:
从组件中的任何位置或将功能注入其他组件
Let's say that you will update the user:
You can call:
From any place in your component or inject the function into other components