Skip to content

fix(query-core): update initialData when an observer mounts while a Query without data exists#9620

Merged
TkDodo merged 1 commit intomainfrom
feature/initialData
Sep 5, 2025
Merged

fix(query-core): update initialData when an observer mounts while a Query without data exists#9620
TkDodo merged 1 commit intomainfrom
feature/initialData

Conversation

@TkDodo
Copy link
Collaborator

@TkDodo TkDodo commented Sep 5, 2025

initialData gives the guarantee that data cannot be undefined, but this falls short when you create a Query via prefetching, and then mount the observer that has initialData set.

That's because initialData is only doing something in the constructor of the Query, so if the Observer isn't the one who creates the Query, it does nothing

This fix makes sure that when new options are applied on a Query (which e.g. happens when an observer mounts), initialData is taken into account when the Query doesn't have any data yet

Summary by CodeRabbit

  • Bug Fixes

    • Initial data is now correctly applied when a query exists without data, so observers receive the provided initialData immediately. State transitions remain consistent as network data arrives, with no API changes.
  • Tests

    • Added comprehensive tests covering initialData and updatedAt behavior, fetch status transitions, and reset semantics to ensure reliable query state handling.

…uery without data exists

initialData gives the guarantee that data cannot be undefined, but this falls short when you create a Query via prefetching, and then mount the observer that has initialData set.

That's because initialData is only doing something in the constructor of the Query, so if the Observer isn't the one who creates the Query, it does nothing

This fix makes sure that when new options are applied on a Query (which e.g. happens when an observer mounts), initialData is taken into account when the Query doesn't have any data yet
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 5, 2025

Walkthrough

Introduces logic in Query.setOptions to seed initialData into state when no data exists, and adds a unit test verifying state transitions with initialData, prefetch, resolution, and reset behaviors. No public API signatures changed.

Changes

Cohort / File(s) Summary
Core logic: initialData seeding
packages/query-core/src/query.ts
In Query.setOptions, when state.data is undefined, compute default state via getDefaultState and, if it has data, setData with manual update and record initial state. Updates GC handling remains intact.
Tests: initialData behavior
packages/query-core/src/__tests__/query.test.tsx
Adds test validating that initialData and initialDataUpdatedAt are applied when a Query exists without data, then replaced by fetched data, and restored on reset.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant C as Client
  participant QC as QueryCache
  participant Q as Query
  participant O as QueryObserver
  participant FN as queryFn

  C->>QC: prefetchQuery(key, queryFn, { staleTime })
  QC->>Q: ensureQuery(key)
  Q->>FN: fetch (in-flight)
  Note over Q: state: data=undefined<br/>status=pending, fetchStatus=fetching

  C->>O: new QueryObserver({ initialData, initialDataUpdatedAt })
  O->>Q: setOptions(...)
  Q->>Q: getDefaultState(options)
  alt no current data and defaultState has data
    Q->>Q: setData(initialData, { manual:true, updatedAt: initialDataUpdatedAt })
  end
  O->>O: subscribe and receive state (success, fetching)

  FN-->>Q: resolve('data')
  Q-->>O: notify state (data='data', success, idle)

  C->>QC: reset query(key)
  QC->>Q: reset()
  Q-->>O: notify state (initialData, idle)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested labels

package: query-core

Poem

A whisk of code, a hop of state,
I stash a snack—initialData on my plate.
Fetch winds blow, new carrots appear,
I nibble the latest, then keep the old near.
Reset the burrow, cache made neat—
Back to my stash, a timely treat! 🥕🐇

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feature/initialData

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@nx-cloud
Copy link

nx-cloud bot commented Sep 5, 2025

View your CI Pipeline Execution ↗ for commit a6269e9

Command Status Duration Result
nx affected --targets=test:sherif,test:knip,tes... ✅ Succeeded 1m 14s View ↗

☁️ Nx Cloud last updated this comment at 2025-09-05 14:02:57 UTC

@pkg-pr-new
Copy link

pkg-pr-new bot commented Sep 5, 2025

More templates

@tanstack/angular-query-devtools-experimental

npm i https://pkg.pr.new/@tanstack/angular-query-devtools-experimental@9620

@tanstack/angular-query-experimental

npm i https://pkg.pr.new/@tanstack/angular-query-experimental@9620

@tanstack/eslint-plugin-query

npm i https://pkg.pr.new/@tanstack/eslint-plugin-query@9620

@tanstack/query-async-storage-persister

npm i https://pkg.pr.new/@tanstack/query-async-storage-persister@9620

@tanstack/query-broadcast-client-experimental

npm i https://pkg.pr.new/@tanstack/query-broadcast-client-experimental@9620

@tanstack/query-core

npm i https://pkg.pr.new/@tanstack/query-core@9620

@tanstack/query-devtools

npm i https://pkg.pr.new/@tanstack/query-devtools@9620

@tanstack/query-persist-client-core

npm i https://pkg.pr.new/@tanstack/query-persist-client-core@9620

@tanstack/query-sync-storage-persister

npm i https://pkg.pr.new/@tanstack/query-sync-storage-persister@9620

@tanstack/react-query

npm i https://pkg.pr.new/@tanstack/react-query@9620

@tanstack/react-query-devtools

npm i https://pkg.pr.new/@tanstack/react-query-devtools@9620

@tanstack/react-query-next-experimental

npm i https://pkg.pr.new/@tanstack/react-query-next-experimental@9620

@tanstack/react-query-persist-client

npm i https://pkg.pr.new/@tanstack/react-query-persist-client@9620

@tanstack/solid-query

npm i https://pkg.pr.new/@tanstack/solid-query@9620

@tanstack/solid-query-devtools

npm i https://pkg.pr.new/@tanstack/solid-query-devtools@9620

@tanstack/solid-query-persist-client

npm i https://pkg.pr.new/@tanstack/solid-query-persist-client@9620

@tanstack/svelte-query

npm i https://pkg.pr.new/@tanstack/svelte-query@9620

@tanstack/svelte-query-devtools

npm i https://pkg.pr.new/@tanstack/svelte-query-devtools@9620

@tanstack/svelte-query-persist-client

npm i https://pkg.pr.new/@tanstack/svelte-query-persist-client@9620

@tanstack/vue-query

npm i https://pkg.pr.new/@tanstack/vue-query@9620

@tanstack/vue-query-devtools

npm i https://pkg.pr.new/@tanstack/vue-query-devtools@9620

commit: a6269e9

@github-actions
Copy link
Contributor

github-actions bot commented Sep 5, 2025

Sizes for commit a6269e9:

Branch Bundle Size
Main
This PR

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (3)
packages/query-core/src/query.ts (1)

208-219: Minor: clarify guard and avoid unnecessary work

  • Add an inline reason for the ESLint disable (state can be undefined during constructor’s initial setOptions).
  • Micro-optimization: short-circuit when no initialData is provided to avoid computing defaultState.

Apply:

     this.updateGcTime(this.options.gcTime)

-    // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
-    if (this.state && this.state.data === undefined) {
+    // During construction, `this.state` is undefined; this guard is required.
+    // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
+    const hasInitial =
+      this.options.initialData !== undefined ||
+      typeof this.options.initialData === 'function'
+    if (this.state && this.state.data === undefined && hasInitial) {
       const defaultState = getDefaultState(this.options)
       if (defaultState.data !== undefined) {
         this.setData(defaultState.data, {
           updatedAt: defaultState.dataUpdatedAt,
           manual: true,
         })
         this.#initialState = defaultState
       }
     }
packages/query-core/src/__tests__/query.test.tsx (2)

1196-1256: Use async timer advancement to avoid flakiness

Swap to advanceTimersByTimeAsync for deterministic resolution of pending promises, and await both calls.

Apply:

-    vi.advanceTimersByTime(50)
+    await vi.advanceTimersByTimeAsync(50)
@@
-    vi.advanceTimersByTime(50)
+    await vi.advanceTimersByTimeAsync(50)

1248-1248: Fix typo in test comment

“ot” → “to”.

Apply:

-    // resetting should get us back ot 'initialData'
+    // resetting should get us back to 'initialData'
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between b43af57 and a6269e9.

📒 Files selected for processing (2)
  • packages/query-core/src/__tests__/query.test.tsx (1 hunks)
  • packages/query-core/src/query.ts (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (2)
packages/query-core/src/query.ts (1)
packages/query-core/src/mutation.ts (1)
  • getDefaultState (349-366)
packages/query-core/src/__tests__/query.test.tsx (2)
packages/query-core/src/utils.ts (1)
  • sleep (363-367)
packages/query-core/src/query.ts (1)
  • promise (198-200)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: Preview
  • GitHub Check: Test
🔇 Additional comments (1)
packages/query-core/src/query.ts (1)

208-219: Initial data seeding on setOptions is correct

This achieves the intended behavior: seeds initialData only when no data exists, preserves fetchStatus via a manual success, and updates #initialState for reset. LGTM.

@codecov
Copy link

codecov bot commented Sep 5, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 59.62%. Comparing base (a0b96db) to head (a6269e9).
⚠️ Report is 2 commits behind head on main.

Additional details and impacted files

Impacted file tree graph

@@             Coverage Diff             @@
##             main    #9620       +/-   ##
===========================================
+ Coverage   45.47%   59.62%   +14.15%     
===========================================
  Files         209      138       -71     
  Lines        8372     5615     -2757     
  Branches     1905     1511      -394     
===========================================
- Hits         3807     3348      -459     
+ Misses       4118     1963     -2155     
+ Partials      447      304      -143     
Components Coverage Δ
@tanstack/angular-query-devtools-experimental ∅ <ø> (∅)
@tanstack/angular-query-experimental 87.00% <ø> (ø)
@tanstack/eslint-plugin-query ∅ <ø> (∅)
@tanstack/query-async-storage-persister 43.85% <ø> (ø)
@tanstack/query-broadcast-client-experimental 24.39% <ø> (ø)
@tanstack/query-codemods ∅ <ø> (∅)
@tanstack/query-core 97.48% <100.00%> (+<0.01%) ⬆️
@tanstack/query-devtools 3.48% <ø> (ø)
@tanstack/query-persist-client-core 79.60% <ø> (ø)
@tanstack/query-sync-storage-persister 84.61% <ø> (ø)
@tanstack/query-test-utils ∅ <ø> (∅)
@tanstack/react-query 96.00% <ø> (ø)
@tanstack/react-query-devtools 10.00% <ø> (ø)
@tanstack/react-query-next-experimental ∅ <ø> (∅)
@tanstack/react-query-persist-client 100.00% <ø> (ø)
@tanstack/solid-query 78.13% <ø> (ø)
@tanstack/solid-query-devtools ∅ <ø> (∅)
@tanstack/solid-query-persist-client 100.00% <ø> (ø)
@tanstack/svelte-query 87.58% <ø> (ø)
@tanstack/svelte-query-devtools ∅ <ø> (∅)
@tanstack/svelte-query-persist-client 100.00% <ø> (ø)
@tanstack/vue-query 71.10% <ø> (ø)
@tanstack/vue-query-devtools ∅ <ø> (∅)
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@TkDodo TkDodo merged commit 1c8a921 into main Sep 5, 2025
9 of 10 checks passed
@TkDodo TkDodo deleted the feature/initialData branch September 5, 2025 14:13
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant