Skip to content
Source
Sign inSign up
TanStack/query

`useQuery` with `initialData` is returning `undefined` data when another query with the same key a no `initialData` is fetching #6968

Closednelyousfi(GitHub profile, opens in a new tab) opened this issue 3 comments

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

  1. Start a query without initial data.
  2. While the first query is still fetching, start a second one with the same key but this time with initial data.
  3. 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.

  1. oh interesting. So conceptually, I think this is how it's designed to work. initialData is only taken into account when the Query is created in the cache, which in your case happens when you call prefetchQuery.

    When your component renders, it will pick up the already existing Query and initialData is ignored.

    So overall, this is a typings issue at best. I was very reluctant to add any guarantees on data always being defined, and really thought that when initialData is 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 | undefined even if initialData is 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

  2. TkDodo closed this

  3. TkDodo added labelstypes

  4. TkDodo added labelsknown limitation

  5. Interesting discussion.

    Since this is a typings issue, I do wonder if there's some consideration to infer return type based on the query key? Perhaps this already digresses to a discussion on key management, but I do believe that in almost all cases, the expectation would be that a single return type exists given a key, regardless of that key being used in prefetchQuery or useQuery.

  6. well with queryOptions, we can infer the return type when a key is used depending on what the quryFn returns. But that doesn't help us with adding | undefined to the union or not

Sign in to join this conversation.