I want to cancel pending calls on unmount of a component. I’m using react query 3.39.2. There are n api calls, and the query key is dynamic. I’ve shared the current code below, and it does not work. What am I doing wrong?
PS: It does go inside the if block.
const queryClinet = useQueryClient();
useEffect(() => {
return () => {
queryClient.getQueryCache()
.getAll()
.forEach(query => {
if(query.queryKey.includes('partOfMyKey'))
queryClient.cancelQueries(query.queryKey);
// queryClient.cancelQueries({ queryKey: query.queryKey });
})
}
}, [window.location.href])
2
Answers
You are almost there and missing a curly braces {} in your if statement.The code should be this :
Query Cancellation alone doesn’t do much per default: It cancels the Query itself (so data is not stored), but it doesn’t abort the request.
To achieve that, you need to forward the
AbortSignal
provided by react-query to your fetch function. How you do this depends on what you use for data fetching – the docs have multiple examples, but here is the one forfetch
:If the
signal
is passed tofetch
, the Query will be cancelled automatically when the fetch is aborted. This will happen as soon as no component is mounted that is actively using the Query.