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?
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
const request = myTriggerFunction()
// ...
request.abort()