Query Cancellation
Can someone sanity-check my React Query cancel logic?
Stack: React 18, TanStack Query v5, axios 1.9
I have a hook:
When I switch context, modelName changes ('milestone' → 'milestone_item'), so the key changes. The old request stays (pending) in the Network tab and never aborts. I tried:
Passing signal (as above)
Adding
signal.addEventListener('abort', ...)
→ never logs
Manually calling queryClient.cancelQueries({ queryKey: ['media'], exact: false })
in a useEffect and before state changes → still no abort / no log
Question:
What’s the correct way to cancel an in-flight query when switching to a different key? Do I have to cancel before triggering the state change that mounts the new query, or is there a cleaner pattern for this use case?
Any gotchas with axios + AbortSignal or React Query observers I’m missing? Thanks!2 Replies
rising-crimson•2mo ago
I guess it doesn't matter? The old query will eventually get garbage collected if it has no observers.
By default, queries that unmount or become unused before their promises are resolved are not cancelled. This means that after the promise has resolved, the resulting data will be available in the cache. This is helpful if you've started receiving a query, but then unmount the component before it finishes. If you mount the component again and the query has not been garbage collected yet, data will be available.https://tanstack.com/query/latest/docs/framework/react/guides/query-cancellation But looks like it can also be cancelled if that's what you want
exotic-emeraldOP•2mo ago
I see. For some reason, a particular set of actions at a certain time causes my page to become unresponsive. I thought the queries were at fault but looks like something else is happening.