Skip to content
Source
Sign inSign up
TanStack/query

Query cancellation does not work with Suspense #5103

Send to my agent
Closedbug-brain(GitHub profile, opens in a new tab) opened this issue 3 comments

Describe the bug

Consuming an AbortSignal does enable automatic query cancellation if suspense mode is used. When the component unmounts while the query function is not resolved the query is visible in the dev tools without any observers.

Your minimal, reproducible example

https://codesandbox.io/s/magical-shape-hbf7l4

Steps to reproduce

  1. load the sandbox
  2. wait for the timeout / until the page shows “done“
  3. the console is still empty because there was no abort event on the signal

Expected behavior

I expected that the automatic cancellation works both for suspense: false and suspense: true. That includes the unobserved query being garbage collected.

How often does this bug happen?

Every time

Screenshots or Videos

No response

Platform

  • OS: Linux
  • Browser: Firefox

TanStack Query version

4.26.1

TypeScript version

4.1.3

Additional context

From what I can tell be glancing at the problem this has to do with useSyncExternalStore which is used by useQuery. When the component suspends React never subscribes and consequently never unsubscribes which would trigger removing the observer and in turn abort being called.

  1. Yeah I don't think this can work. Query cancellation works on observer level. If the last observer unsubscribes while the query is in-flight, the query will be cancelled.

    With suspense, we never get to the point where the observer even subscribes, because suspending happens up-front.

    I don't think there is a way how we can distinguish between "the component unmounts because of suspense" vs. "the component unmounts because I'm not rendering it". If you have a component that unmounts the suspense boundary, I would setup a useEffect there that calls queryClient.cancelQueries({ queryKey }) manually.

  2. TkDodo added labelssuspense

  3. If this is a limitation of React it would be nice if the docs mentioned it because that is the first place people look.

  4. Sure, PRs welcome

  5. TkDodo closed this

Sign in to join this conversation.