fix: no hydration when new promise comes in #8383
main fromrefs/pull/8383/head·merged by TkDodo View on GitHubNo description provided.
- 1
github-actions[bot](GitHub profile, opens in a new tab) added labelspackage: query-core
Open in Stackblitz
More templates
- @tanstack/query-example-angular-auto-refetching
- @tanstack/query-example-angular-basic
- @tanstack/query-example-angular-devtools-panel
- @tanstack/query-example-angular-infinite-query-with-max-pages
- @tanstack/query-example-angular-pagination
- @tanstack/query-example-angular-router
- @tanstack/query-example-angular-rxjs
- @tanstack/query-example-angular-query-options-from-a-service
- @tanstack/query-example-angular-simple
- @tanstack/query-example-react-auto-refetching
- @tanstack/query-example-react-algolia
- @tanstack/query-example-react-basic
- @tanstack/query-example-react-basic-graphql-request
- @tanstack/query-example-react-default-query-function
- @tanstack/query-example-react-devtools-panel
- @tanstack/query-example-react-infinite-query-with-max-pages
- @tanstack/query-example-react-load-more-infinite-scroll
- @tanstack/query-example-react-nextjs
- @tanstack/query-example-react-nextjs-app-prefetching
- @tanstack/query-example-react-offline
- @tanstack/query-example-nextjs-suspense-streaming
- @tanstack/query-example-react-optimistic-updates-cache
- @tanstack/query-example-react-optimistic-updates-ui
- @tanstack/query-example-react-pagination
- @tanstack/query-example-react-playground
- @tanstack/query-example-react-prefetching
- @tanstack/query-example-react-react-native
- @tanstack/query-example-react-router
- @tanstack/query-example-react-rick-morty
- @tanstack/query-example-react-shadow-dom
- @tanstack/query-example-react-simple
- @tanstack/query-example-react-star-wars
- @tanstack/query-example-react-suspense
- @tanstack/query-example-solid-astro
- @tanstack/query-example-solid-basic
- @tanstack/query-example-solid-basic-graphql-request
- @tanstack/query-example-solid-default-query-function
- @tanstack/query-example-solid-simple
- @tanstack/query-example-solid-start-streaming
- @tanstack/query-example-vue-2.6-basic
- @tanstack/query-example-vue-2.7-basic
- @tanstack/query-example-vue-basic
- @tanstack/query-example-vue-dependent-queries
- @tanstack/query-example-vue-nuxt3
- @tanstack/query-example-vue-persister
- @tanstack/query-example-vue-simple
- @tanstack/query-example-svelte-auto-refetching
- @tanstack/query-example-svelte-basic
- @tanstack/query-example-svelte-load-more-infinite-scroll
- @tanstack/query-example-svelte-optimistic-updates
- @tanstack/query-example-svelte-playground
- @tanstack/query-example-svelte-simple
- @tanstack/query-example-svelte-ssr
- @tanstack/query-example-svelte-star-wars
@tanstack/angular-query-devtools-experimental
npm i https://pkg.pr.new/@tanstack/angular-query-devtools-experimental@8383@tanstack/eslint-plugin-query
npm i https://pkg.pr.new/@tanstack/eslint-plugin-query@8383@tanstack/angular-query-experimental
npm i https://pkg.pr.new/@tanstack/angular-query-experimental@8383@tanstack/query-async-storage-persister
npm i https://pkg.pr.new/@tanstack/query-async-storage-persister@8383@tanstack/query-core
npm i https://pkg.pr.new/@tanstack/query-core@8383@tanstack/query-broadcast-client-experimental
npm i https://pkg.pr.new/@tanstack/query-broadcast-client-experimental@8383@tanstack/query-devtools
npm i https://pkg.pr.new/@tanstack/query-devtools@8383@tanstack/query-persist-client-core
npm i https://pkg.pr.new/@tanstack/query-persist-client-core@8383@tanstack/query-sync-storage-persister
npm i https://pkg.pr.new/@tanstack/query-sync-storage-persister@8383@tanstack/react-query
npm i https://pkg.pr.new/@tanstack/react-query@8383@tanstack/react-query-devtools
npm i https://pkg.pr.new/@tanstack/react-query-devtools@8383@tanstack/react-query-next-experimental
npm i https://pkg.pr.new/@tanstack/react-query-next-experimental@8383@tanstack/react-query-persist-client
npm i https://pkg.pr.new/@tanstack/react-query-persist-client@8383@tanstack/solid-query
npm i https://pkg.pr.new/@tanstack/solid-query@8383@tanstack/solid-query-devtools
npm i https://pkg.pr.new/@tanstack/solid-query-devtools@8383@tanstack/solid-query-persist-client
npm i https://pkg.pr.new/@tanstack/solid-query-persist-client@8383@tanstack/svelte-query
npm i https://pkg.pr.new/@tanstack/svelte-query@8383@tanstack/svelte-query-devtools
npm i https://pkg.pr.new/@tanstack/svelte-query-devtools@8383@tanstack/svelte-query-persist-client
npm i https://pkg.pr.new/@tanstack/svelte-query-persist-client@8383@tanstack/vue-query
npm i https://pkg.pr.new/@tanstack/vue-query@8383@tanstack/vue-query-devtools
npm i https://pkg.pr.new/@tanstack/vue-query-devtools@8383commit:
8c2023ereally weird, queryFn is getting called and returns the updated value, but the serializer is called only with teh initial count
before digging deeper, can you confirm if this is a bug or expected @TkDodo ?
I think we might not be in a pending state so the promise doesn't get sent down?
juliusmarminge reviewed
packages/query-core/src/__tests__/hydration.test.tsx lines 1121 to 1125Outdated@@ -1068,0 +1105,21 @@1105+1106+ hydrate(clientQueryClient, dehydrated)1107+1108+ await promise1109+ await waitFor(() =>1110+ expect(clientQueryClient.getQueryData(query.queryKey)).toBe(0),1111+ )1112+1113+ console.log('serialize mock', serializeDataMock.mock.calls)1114+1115+ expect(serializeDataMock).toHaveBeenCalledTimes(1)1116+ expect(serializeDataMock).toHaveBeenCalledWith(0)1117+1118+ expect(deserializeDataMock).toHaveBeenCalledTimes(1)1119+ expect(deserializeDataMock).toHaveBeenCalledWith(0)1120+1121+ // --- server ---1122+ countRef.current++1123+ const promise2 = serverQueryClient.prefetchQuery(query)1124+1125+ const dehydrated2 = dehydrate(serverQueryClient)assume this is a server fn calling
revalidatePath()so the page re-rendersyou’re right: we only send the promise when we are in
pendingstate. The fix is likely to send the promise when we are infetchStatus: 'fetching'instead 💡i believe another issue is we're getting
dataUpdatedAt: 0so it does't rehydratefeels like we need some other state that would let us know if the promise is fresher then we need to set the queries' promise or something.. this goes deeper than I thought
github-actions[bot](GitHub profile, opens in a new tab) added labelspackage: react-query
I'd say if we get a promise, we should always assume it's newer and hydrate its data, no?
how do we check for that wihtout causing infinite re-renders in
<HydrationBoundary>?struggling to figuring out how to properly filter out the queries to put in the hydration queue
https://github.com/user-attachments/assets/2b6bf540-e735-4eca-a549-e15ab223c1de
@juliusmarminge have you widened this check?
to something like:
const hydrationIsNewer = dehydratedQuery.state.dataUpdatedAt > existingQuery.state.dataUpdatedAt || dehydratedQuery.promiseso that whenever a promise is included, we put it the queue.
yea that causes infinite rerenders
interesting; let’s debug that together today if you have some time?
interesting; let’s debug that together today if you have some time?
sure! what time? I can sneak in a short seesion anytime after 10am gmt+1.
I pinged you on discord ;)
juliusmarminge reviewed
packages/react-query/src/HydrationBoundary.tsx line 91Outdated@@ -68,9 +73,19 @@6873 for (const dehydratedQuery of queries) {6974 const existingQuery = queryCache.get(dehydratedQuery.queryHash)707576+ // console.log(77+ // '[HydrationBoundary] existingQuery',78+ // JSON.stringify(existingQuery?.state, null, 2),79+ // )80+ // console.log(81+ // '[HydrationBoundary] dehydratedQuery',82+ // JSON.stringify(dehydratedQuery.state, null, 2),83+ // )7184 if (!existingQuery) {7285 newQueries.push(dehydratedQuery)7386 } else {7487 const hydrationIsNewer =7588 dehydratedQuery.state.dataUpdatedAt >76- existingQuery.state.dataUpdatedAt89+ existingQuery.state.dataUpdatedAt ||90+ // @ts-expect-error91+ dehydratedQuery.promise?.status !== existingQuery.promise?.statusthis might actually be working
What if we prefetch a query without
awaitin a page that is static or cached, either fully or partially, and then client navigate to it with newer data in the cache? My guess is that there are/can be situations where we get a promise that will resolve to data that is actually older than the one we have on the client already?Maybe the entirely correct way to do this would be to inspect the data the query resolves to before determining whether to update the cache with that data? Implementation-wise that's a lot tricker though unfortunately. :(
Maybe the entirely correct way to do this would be to inspect the data the query resolves to
this is something only users could verify though. Without query meta-data like
dataUpdatedAt, react-query doesn’t know the age of the data. Are you suggesting we provide a way for users to extract a timestamp (age) from the promise data in some sort of callback option?Is it? If we are using the fetch timestamp from the server to determine this when hydrating data, we can surely do that for promises too, just after they resolved? I'm sure it might be a big painful thing to implement, but is there some inherent thing about user/library land that blocks us from doing this in the library using the same logic?
To be clear, if we already have this query in the cache, this might require us to wait for the promise outside of the cache and only put the data in. Or even worse, to support fetching states properly, it might requires us to have some sort of "possibleUpdatePromise" or something that would not commit it's result to the cache if it's older.
@juliusmarminge the tests failures are happening because the tests hang indefinitely. Even locally,
vitestnever terminates. If I remove this line of code, everything is back to normal :/How do you run the tests locally? When I run
vitestfrom thequery-coredirectory all tests pass?it’s the
react-querytests that are failing. So go topackages/react-queryand dopnpm run test:libthere.Oh - I wonder if that's cause we're not testing with the same type of promises that RSCs are sending down 🥹🥹
Can look later tonight when I get home
@juliusmarminge what are we gonna do with this one?
Sorry completely forgot about this 😅
I think I had it sort of working but happy to jump on a call and talk about it still! Hit me up on discord when you have some time to go over it!
@juliusmarminge we’re now getting a build error for the react15 example:
Error occurred prerendering page "/". Read more: https://nextjs.org/docs/messages/prerender-error Error: redacted at /home/workflows/workspace/integrations/react-next-15/.next/server/chunks/750.js:1:41244 at process.processTicksAndRejections (node:internal/process/task_queues:95:5)do you know why that is?
@juliusmarminge we’re now getting a build error for the react15 example:
Error occurred prerendering page "/". Read more: https://nextjs.org/docs/messages/prerender-error Error: redacted at /home/workflows/workspace/integrations/react-next-15/.next/server/chunks/750.js:1:41244 at process.processTicksAndRejections (node:internal/process/task_queues:95:5)do you know why that is?
seems like something is running at build that should run at request time? what's the unredacted error?
what's the unredacted error?
I wish I knew 😂. How can we find out?
what's the unredacted error?
I wish I knew 😂. How can we find out?
I was able to find the error by passing
NODE_ENV=developmentto thebuildcommand.❯ NODE_ENV=development pnpm build > react-next-15@ build /Users/mstramel/GitHub/query/integrations/react-next-15 > next build ⚠ You are using a non-standard "NODE_ENV" value in your environment. This creates inconsistencies in the project and is strongly advised against. Read more: https://nextjs.org/docs/messages/non-standard-node-env ▲ Next.js 15.1.2 Creating an optimized production build ... ✓ Compiled successfully Skipping linting ✓ Checking validity of types ✓ Collecting page data Error occurred prerendering page "/_not-found". Read more: https://nextjs.org/docs/messages/prerender-error TypeError: Cannot read properties of null (reading 'useEffect') at t.useEffect (/Users/mstramel/GitHub/query/node_modules/.pnpm/next@15.1.2_@babel+core@7.26.0_babel-plugin-react-compiler@0.0.0_react-dom@19.0.0_react@19.0.0__react@19.0.0_sass@1.81.0/node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js:68:6422) at o (/Users/mstramel/GitHub/query/integrations/react-next-15/.next/server/chunks/379.js:1:18168) at react-stack-bottom-frame (/Users/mstramel/GitHub/query/node_modules/.pnpm/next@15.1.2_@babel+core@7.26.0_babel-plugin-react-compiler@0.0.0_react-dom@19.0.0_react@19.0.0__react@19.0.0_sass@1.81.0/node_modules/next/dist/compiled/next-server/app-page.runtime.dev.js:25:229305) at renderWithHooks (/Users/mstramel/GitHub/query/node_modules/.pnpm/next@15.1.2_@babel+core@7.26.0_babel-plugin-react-compiler@0.0.0_react-dom@19.0.0_react@19.0.0__react@19.0.0_sass@1.81.0/node_modules/next/dist/compiled/next-server/app-page.runtime.dev.js:25:66965) at renderElement (/Users/mstramel/GitHub/query/node_modules/.pnpm/next@15.1.2_@babel+core@7.26.0_babel-plugin-react-compiler@0.0.0_react-dom@19.0.0_react@19.0.0__react@19.0.0_sass@1.81.0/node_modules/next/dist/compiled/next-server/app-page.runtime.dev.js:25:81693) at retryNode (/Users/mstramel/GitHub/query/node_modules/.pnpm/next@15.1.2_@babel+core@7.26.0_babel-plugin-react-compiler@0.0.0_react-dom@19.0.0_react@19.0.0__react@19.0.0_sass@1.81.0/node_modules/next/dist/compiled/next-server/app-page.runtime.dev.js:25:140140) at renderNodeDestructive (/Users/mstramel/GitHub/query/node_modules/.pnpm/next@15.1.2_@babel+core@7.26.0_babel-plugin-react-compiler@0.0.0_react-dom@19.0.0_react@19.0.0__react@19.0.0_sass@1.81.0/node_modules/next/dist/compiled/next-server/app-page.runtime.dev.js:25:136545) at finishFunctionComponent (/Users/mstramel/GitHub/query/node_modules/.pnpm/next@15.1.2_@babel+core@7.26.0_babel-plugin-react-compiler@0.0.0_react-dom@19.0.0_react@19.0.0__react@19.0.0_sass@1.81.0/node_modules/next/dist/compiled/next-server/app-page.runtime.dev.js:25:67975) at renderElement (/Users/mstramel/GitHub/query/node_modules/.pnpm/next@15.1.2_@babel+core@7.26.0_babel-plugin-react-compiler@0.0.0_react-dom@19.0.0_react@19.0.0__react@19.0.0_sass@1.81.0/node_modules/next/dist/compiled/next-server/app-page.runtime.dev.js:25:83174) at renderElement (/Users/mstramel/GitHub/query/node_modules/.pnpm/next@15.1.2_@babel+core@7.26.0_babel-plugin-react-compiler@0.0.0_react-dom@19.0.0_react@19.0.0__react@19.0.0_sass@1.81.0/node_modules/next/dist/compiled/next-server/app-page.runtime.dev.js:25:135151) Export encountered an error on /_not-found/page: /_not-found, exiting the build. ⨯ Static worker exited with code: 1 and signal: null ELIFECYCLE Command failed with exit code 1.Possibly related to https://github.com/vercel/next.js/issues/65447
UPDATE: Updated to 15.1.6 and got a similar error but different.
Error occurred prerendering page "/404". Read more: https://nextjs.org/docs/messages/prerender-error Error: <Html> should not be imported outside of pages/_document. Read more: https://nextjs.org/docs/messages/no-document-import-in-pageSeems like something with Next.js 15
export const dynamic = "force-dynamic"on app/page.tsx also makes it go away, so it seems like it doesn't identify that the page is doing a dynamic fetch call 🤔OK I managed to fix this, but it means that Next.js internals are leaking into
query-core:With this rethrow we get a dynamic page without any force-dynamic directives
juliusmarminge reviewed
OutdatedResolvedby juliusmarminge@@ -82,3 +82,6 @@8282 queryHash: query.queryHash,8383 ...(query.state.status === 'pending' && {8484 promise: query.promise?.then(serializeData).catch((error) => {85+ if ('digest' in error && error.digest === 'DYNAMIC_SERVER_USAGE') {86+ return Promise.reject(error)87+ }i'm assuming we don't want these codes to leak into query-core, so should the
defaultQueryOptionstake someonPrefetchError/onPromise...or similar prop that let's you specify these errors you want to be re-thrown. I'm guessing you might wantnotFound(),redirect()errors to have a similar behavior since those are also throwing next internal codes that aren't meant to be caughtAdded a
shouldRedactErroroption that let's you control whether or not the error should be redacted on dehydration: https://github.com/TanStack/query/pull/8383/commits/75849289ba1bf90bf3a24cf31c0c90d3f083e54bwe’d need to document this too please
done
Hmm seems like the CI test run is running out of memory 👀 https://cloud.nx.app/runs/Qjh3Jk3Wxc/task/%40tanstack%2Freact-query%3Atest%3Alib
github-actions[bot](GitHub profile, opens in a new tab) added labelsdocumentation
Can you help me get the PR checks passing @TkDodo and/or @Ephem ?
Codecov Report#
Attention: Patch coverage is
62.50000%with6 linesin your changes missing coverage. Please review.Project coverage is 63.06%. Comparing base (
bb25d06) to head (8c2023e). Report is 2 commits behind head on main.Additional details and impacted files
@@ Coverage Diff @@ ## main #8383 +/- ## =========================================== + Coverage 46.25% 63.06% +16.80% =========================================== Files 199 135 -64 Lines 7534 4852 -2682 Branches 1721 1365 -356 =========================================== - Hits 3485 3060 -425 + Misses 3670 1547 -2123 + Partials 379 245 -134TkDodo merged this6ca0eb7
TkDodo closed this
Thank you @juliusmarminge and @TkDodo for all the work to get his fixed! We appreciate the hard work!
Sign in to join this conversation.
View your CI Pipeline Execution ↗ for commit 8c2023e7a6e89176c4b26210d98e49033cfc1dbd.
nx affected --targets=test:sherif,test:knip,tes...nx run-many --target=build --exclude=examples/*...☁️ Nx Cloud last updated this comment at
2025-02-17 12:35:04UTC