[react-query] useSuspenseQueries does not throw on errors after queryKey change #6392
Send to my agentDescribe the bug#
useSuspenseQuery does not throw errors occurring in queryFn and returns data as undefined, when queryFn was invoked in reaction to a state change.
See example and repro steps for more information.
Your minimal, reproducible example#
https://codesandbox.io/s/react-query-usesuspensequery-does-not-throw-on-querykey-change-lpgyl9
Steps to reproduce#
- Setup a standard query client, provider, suspense and error boundary
- Setup a query that loads something based on a prop or state (for example loading a post by id)
- Have the query succeed on first render
- Make a state change, for example changing the desired post to a non-existing id (and have your loading logic throw an error when the post is not found)
- Observe that the return value of useSuspenseQuery has the property
dataset toundefinedanderrorto the error thrown inqueryFn
In my minimal example, clicking the "Should fail" button toggles a shouldFail flag to true, making queryFn throw an error, resulting in the described behavior. Clicking the button a second time makes useSuspenseQuery throw and trigger the ErrorBoundary.
Expected behavior#
I would expect useSuspenseQuery to throw when there was no data available for the current queryKey, not for the previous invocation.
How often does this bug happen?#
Every time
Screenshots or Videos#
No response
Platform#
Windows, behavior observed in both Firefox and Chrome.
Tanstack Query adapter#
react-query
TanStack Query version#
5.8.4
TypeScript version#
No response
Additional context#
I've done some digging myself, looking at defaultThrowOnError and noticed that query.queryKey matches the previous query key, rather than the current and the data that indeed belongs to that previous queryKey. This data is not undefined, and thus no throw happens.
TkDodo added labelsbug
TkDodo added labelssuspense
TkDodo added labelspackage: react-query
TkDodo assignedTkDodo
Thanks for confirming.
A super simple possible solution could be to add something along the lines of:
if (queryResult.data === undefined && queryResult.error) { throw queryResult.error }to useSuspenseQuery, instead of directly returning the result from
useBaseQuery(that's at least close to the userland fix I'll be using for the time being), but probably not the best solution overall and certainly not all that portable touseSuspenseQueries.Thanks, I have a fix already (two potential fixes actually) and will finish it in the next couple of days.
TkDodo closed this
Sign in to join this conversation.
I can confirm that this is a bug. I need to look into it to find out what this is about.
interestingly, it works fine for a normal
useQueryif we manually set:see: https://codesandbox.io/s/react-query-usesuspensequery-does-not-throw-on-querykey-change-forked-s8w99f?file=/src/App.js
so it must be related to how / when suspense re-mounts the component 🤔