Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/fix-use-queries-prefetch-in-render.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@tanstack/react-query': patch
---

Add experimental_prefetchInRender support to useQueries so that React.use(promise) resolves correctly
29 changes: 29 additions & 0 deletions packages/react-query/src/useQueries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import * as React from 'react'
import {
QueriesObserver,
QueryObserver,
isServer,
noop,
notifyManager,
} from '@tanstack/query-core'
Expand All @@ -19,6 +20,7 @@ import {
ensureSuspenseTimers,
fetchOptimistic,
shouldSuspend,
willFetch,
} from './suspense'
import type {
DefinedUseQueryResult,
Expand Down Expand Up @@ -324,5 +326,32 @@ export function useQueries<
throw firstSingleResultWhichShouldThrow.error
}

// Handle experimental_prefetchInRender for each query that has it enabled
if (!isServer) {
const observers = observer.getObservers()
optimisticResult.forEach((result, index) => {
const opts = defaultedQueries[index]
if (
opts?.experimental_prefetchInRender &&
willFetch(result, isRestoring)
) {
const queryObserver = observers[index]
const query = client
.getQueryCache()
.get(opts.queryHash)

const promise = !query?.state.dataUpdateCount
? // New cache entry: fetch immediately to ensure .promise is resolved even if the component is unmounted
fetchOptimistic(opts, queryObserver!, errorResetBoundary)
: // Existing cache entry: subscribe to the "cache promise" to finalize the currentThenable once data comes in
query?.promise

promise?.catch(noop).finally(() => {
queryObserver?.updateResult()
})
}
})
}

return getCombinedResult(trackResult())
}