Describe the bug#
If a component is mounted with a query with initial data, and another query with the same key is still fetching, the returned data is undefined instead of the initial data.
This behavior can cause the app to crash, as it won't be caught by the inferred DefinedUseQueryResult type.
Your minimal, reproducible example#
Codesanbox
Steps to reproduce#
- Start a query without initial data.
- While the first query is still fetching, start a second one with the same key but this time with initial data.
- Notice that the second query is returning
undefined instead of initial data.
Expected behavior#
Expecting the initial data to be returned from the second query.
How often does this bug happen?#
Every time
Screenshots or Videos#
No response
Platform#
All platforms.
Tanstack Query adapter#
react-query
TanStack Query version#
5.22.2
TypeScript version#
No response
Additional context#
When providing initial data, even the inferred DefinedUseQueryResult type suggests that the data will always be defined.
oh interesting. So conceptually, I think this is how it's designed to work.
initialDatais only taken into account when the Query is created in the cache, which in your case happens when you callprefetchQuery.When your component renders, it will pick up the already existing Query and
initialDatais ignored.So overall, this is a typings issue at best. I was very reluctant to add any guarantees on
dataalways being defined, and really thought that wheninitialDatais provided, nothing can go wrong. But I guess there are cases like the one you've described.However, I don't think we're going back on the type definitions to make them
T | undefinedeven ifinitialDatais provided. It's too good of a dx improvement 99% of the time.What you probably want in your case is
placeholderData, which is always taken in to account and doesn't narrow the type.https://codesandbox.io/p/sandbox/react-query-with-initial-data-forked-whffv2