Skip to content
Merged
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
6 changes: 6 additions & 0 deletions .changeset/tall-banks-drop.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@tanstack/react-query': patch
'@tanstack/query-core': patch
---

Avoid unhandled promise rejection errors during de/rehydration of pending queries.
46 changes: 29 additions & 17 deletions packages/query-core/src/hydration.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { tryResolveSync } from './thenable'
import { noop } from './utils'
import type {
DefaultError,
MutationKey,
Expand Down Expand Up @@ -78,6 +79,26 @@ function dehydrateQuery(
serializeData: TransformerFn,
shouldRedactErrors: (error: unknown) => boolean,
): DehydratedQuery {
const promise = query.promise?.then(serializeData).catch((error) => {
if (!shouldRedactErrors(error)) {
// Reject original error if it should not be redacted
return Promise.reject(error)
}
// If not in production, log original error before rejecting redacted error
if (process.env.NODE_ENV !== 'production') {
console.error(
`A query that was dehydrated as pending ended up rejecting. [${query.queryHash}]: ${error}; The error will be redacted in production builds`,
)
}
return Promise.reject(new Error('redacted'))
})

// Avoid unhandled promise rejections
// We need the promise we dehydrate to reject to get the correct result into
// the query cache, but we also want to avoid unhandled promise rejections
// in whatever environment the prefetches are happening in.
promise?.catch(noop)

return {
dehydratedAt: Date.now(),
state: {
Expand All @@ -89,19 +110,7 @@ function dehydrateQuery(
queryKey: query.queryKey,
queryHash: query.queryHash,
...(query.state.status === 'pending' && {
promise: query.promise?.then(serializeData).catch((error) => {
if (!shouldRedactErrors(error)) {
// Reject original error if it should not be redacted
return Promise.reject(error)
}
// If not in production, log original error before rejecting redacted error
if (process.env.NODE_ENV !== 'production') {
console.error(
`A query that was dehydrated as pending ended up rejecting. [${query.queryHash}]: ${error}; The error will be redacted in production builds`,
)
}
return Promise.reject(new Error('redacted'))
}),
promise,
}),
...(query.meta && { meta: query.meta }),
}
Expand Down Expand Up @@ -259,10 +268,13 @@ export function hydrate(
// which will re-use the passed `initialPromise`
// Note that we need to call these even when data was synchronously
// available, as we still need to set up the retryer
void query.fetch(undefined, {
// RSC transformed promises are not thenable
initialPromise: Promise.resolve(promise).then(deserializeData),
})
query
.fetch(undefined, {
// RSC transformed promises are not thenable
initialPromise: Promise.resolve(promise).then(deserializeData),
})
// Avoid unhandled promise rejections
.catch(noop)
}
},
)
Expand Down
6 changes: 0 additions & 6 deletions packages/react-query/src/__tests__/HydrationBoundary.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -451,11 +451,6 @@ describe('React hydration', () => {

const dehydratedState = dehydrate(prefetchQueryClient)

function ignore() {
// Ignore redacted unhandled rejection
}
process.addListener('unhandledRejection', ignore)

// Mimic what React/our synchronous thenable does for already rejected promises
// @ts-expect-error
dehydratedState.queries[0].promise.status = 'failure'
Expand Down Expand Up @@ -484,7 +479,6 @@ describe('React hydration', () => {
await vi.advanceTimersByTimeAsync(21)
expect(rendered.getByText('new')).toBeInTheDocument()

process.removeListener('unhandledRejection', ignore)
hydrateSpy.mockRestore()
prefetchQueryClient.clear()
clientQueryClient.clear()
Expand Down
Loading