Skip to content
Source
Sign inSign up
TanStack/query

fix: no hydration when new promise comes in #8383

Mergedjuliusmarmingemerged 35 commits intomain fromrefs/pull/8383/headmerged by TkDodo View on GitHub

juliusmarmingecommented

No description provided.

    1. github-actions[bot](GitHub profile, opens in a new tab) added labelspackage: query-core

    2. View your CI Pipeline Execution ↗ for commit 8c2023e7a6e89176c4b26210d98e49033cfc1dbd.

      CommandStatusDurationResult
      nx affected --targets=test:sherif,test:knip,tes...✅ Succeeded3m 21sView ↗
      nx run-many --target=build --exclude=examples/*...✅ Succeeded1m 59sView ↗

      ☁️ Nx Cloud last updated this comment at 2025-02-17 12:35:04 UTC

    3. Open in Stackblitz

      More templates

      @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@8383

      commit: 8c2023e

    4. really weird, queryFn is getting called and returns the updated value, but the serializer is called only with teh initial count

      CleanShot 2024-12-02 at 17 16 59

    5. juliusmarmingecommented

      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?

      https://github.com/juliusmarminge/query/blob/cf37452e72e44609e49600f8b7c124cc5a197af5/packages/query-core/src/hydration.ts#L83-L92

    6. 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 promise
      1109+ 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-renders

    7. you’re right: we only send the promise when we are in pending state. The fix is likely to send the promise when we are in fetchStatus: 'fetching' instead 💡

    8. i believe another issue is we're getting dataUpdatedAt: 0 so it does't rehydrate

      CleanShot 2024-12-02 at 19 54 15@2x

    9. feels 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

    10. github-actions[bot](GitHub profile, opens in a new tab) added labelspackage: react-query

    11. I'd say if we get a promise, we should always assume it's newer and hydrate its data, no?

    12. juliusmarmingecommented

      how do we check for that wihtout causing infinite re-renders in <HydrationBoundary> ?

    13. juliusmarmingecommented

      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

    14. @juliusmarminge have you widened this check?

      https://github.com/TanStack/query/blob/8fe90104c6fce9654539e006bd739074e15ae70f/packages/react-query/src/HydrationBoundary.tsx#L74-L76

      to something like:

      const hydrationIsNewer =
        dehydratedQuery.state.dataUpdatedAt >
          existingQuery.state.dataUpdatedAt || dehydratedQuery.promise

      so that whenever a promise is included, we put it the queue.

    15. yea that causes infinite rerenders

    16. interesting; let’s debug that together today if you have some time?

    17. juliusmarmingecommented

      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.

    18. I pinged you on discord ;)

    19. 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)
      7075
      76+ // 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.dataUpdatedAt
      89+ existingQuery.state.dataUpdatedAt ||
      90+ // @ts-expect-error
      91+ dehydratedQuery.promise?.status !== existingQuery.promise?.status
      juliusmarmingecommented

      this might actually be working

      What if we prefetch a query without await in 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. :(

      TkDodocommented

      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, vitest never terminates. If I remove this line of code, everything is back to normal :/

      How do you run the tests locally? When I run vitest from the query-core directory all tests pass?

      it’s the react-query tests that are failing. So go to packages/react-query and do pnpm run test:lib there.

      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

    20. @juliusmarminge what are we gonna do with this one?

    21. 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!

    22. @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?

    23. juliusmarmingecommented

      @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?

    24. what's the unredacted error?

      I wish I knew 😂. How can we find out?

    25. 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=development to the build command.

      image
      ❯ 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-page

      Seems like something with Next.js 15

    26. 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 🤔

    27. juliusmarmingecommented

      OK I managed to fix this, but it means that Next.js internals are leaking into query-core:

      CleanShot 2025-01-26 at 11 41 21@2x

      With this rethrow we get a dynamic page without any force-dynamic directives

    28. juliusmarminge reviewed

      OutdatedResolvedby juliusmarminge
    29. Hmm seems like the CI test run is running out of memory 👀 https://cloud.nx.app/runs/Qjh3Jk3Wxc/task/%40tanstack%2Freact-query%3Atest%3Alib

    30. github-actions[bot](GitHub profile, opens in a new tab) added labelsdocumentation

    31. Can you help me get the PR checks passing @TkDodo and/or @Ephem ?

    32. seems like we’re running into out of memory:

      FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory

      let’s try setting more memory for the test run: 71a4453

    33. Codecov Report

      Attention: Patch coverage is 62.50000% with 6 lines in 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

      Impacted file tree graph

      @@             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      -134     
      ComponentsCoverage Δ
      @tanstack/angular-query-devtools-experimental∅ <ø> (∅)
      @tanstack/angular-query-experimental88.65% <ø> (ø)
      @tanstack/eslint-plugin-query∅ <ø> (∅)
      @tanstack/query-async-storage-persister43.85% <ø> (ø)
      @tanstack/query-broadcast-client-experimental∅ <ø> (∅)
      @tanstack/query-codemods∅ <ø> (∅)
      @tanstack/query-core93.95% <60.00%> (-0.21%):arrow_down:
      @tanstack/query-devtools4.78% <ø> (ø)
      @tanstack/query-persist-client-core57.73% <ø> (ø)
      @tanstack/query-sync-storage-persister84.61% <ø> (ø)
      @tanstack/react-query95.37% <66.66%> (-0.59%):arrow_down:
      @tanstack/react-query-devtools10.00% <ø> (ø)
      @tanstack/react-query-next-experimental∅ <ø> (∅)
      @tanstack/react-query-persist-client100.00% <ø> (ø)
      @tanstack/solid-query78.20% <ø> (ø)
      @tanstack/solid-query-devtools∅ <ø> (∅)
      @tanstack/solid-query-persist-client100.00% <ø> (ø)
      @tanstack/svelte-query87.33% <ø> (ø)
      @tanstack/svelte-query-devtools∅ <ø> (∅)
      @tanstack/svelte-query-persist-client100.00% <ø> (ø)
      @tanstack/vue-query71.01% <ø> (ø)
      @tanstack/vue-query-devtools∅ <ø> (∅)
    34. TkDodo merged this6ca0eb7

    35. TkDodo closed this

    36. Thank you @juliusmarminge and @TkDodo for all the work to get his fixed! We appreciate the hard work!

Sign in to join this conversation.