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?