TanStackT
TanStack6mo ago
3 replies
living-lavender

Query Cancellation

Can someone sanity-check my React Query cancel logic?

Stack: React 18, TanStack Query v5, axios 1.9

I have a hook:

export const useFetchMedia = ({ modelName, modelId, collection }: any) =>
  useQuery({
    queryKey: ['media', modelName, modelId, collection],
    queryFn: ({ signal }) =>
      axios
        .get('/media', { params: { modelName, modelId, collection }, signal })
        .then(r => r.data.data ?? r.data),
  });

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!
Was this page helpful?