Skip to content
Source
Sign inSign up
TanStack/query

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

MergedTkDodomerged 1 commit intomain fromrefs/pull/9620/headmerged by TkDodo View on GitHub

TkDodocommented

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.
    1. coderabbitai[bot](GitHub profile, opens in a new tab)commented

      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)

      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.
    2. github-actions[bot](GitHub profile, opens in a new tab) added labelspackage: query-core

    3. nx-cloud[bot](GitHub profile, opens in a new tab)commented

      View your CI Pipeline Execution ↗ for commit a6269e967c09ec51599d628c502960c201c1b958

      CommandStatusDurationResult
      nx affected --targets=test:sherif,test:knip,tes...✅ Succeeded1m 14sView ↗

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

    4. 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

    5. github-actions[bot](GitHub profile, opens in a new tab)commented

      Sizes for commit a6269e967c09ec51599d628c502960c201c1b958:

      BranchBundle Size
      Main
      This PR
    6. 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 b43af57cd2ccc5b6c3d96c4168e23d1fd811213a and a6269e967c09ec51599d628c502960c201c1b958.

      📒 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.

    7. codecov[bot](GitHub profile, opens in a new tab)commented

      Codecov Report

      :white_check_mark: All modified and coverable lines are covered by tests. :white_check_mark: Project coverage is 59.62%. Comparing base (a0b96db) to head (a6269e9). :warning: 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     
      ComponentsCoverage Δ
      @tanstack/angular-query-devtools-experimental∅ <ø> (∅)
      @tanstack/angular-query-experimental87.00% <ø> (ø)
      @tanstack/eslint-plugin-query∅ <ø> (∅)
      @tanstack/query-async-storage-persister43.85% <ø> (ø)
      @tanstack/query-broadcast-client-experimental24.39% <ø> (ø)
      @tanstack/query-codemods∅ <ø> (∅)
      @tanstack/query-core97.48% <100.00%> (+<0.01%):arrow_up:
      @tanstack/query-devtools3.48% <ø> (ø)
      @tanstack/query-persist-client-core79.60% <ø> (ø)
      @tanstack/query-sync-storage-persister84.61% <ø> (ø)
      @tanstack/query-test-utils∅ <ø> (∅)
      @tanstack/react-query96.00% <ø> (ø)
      @tanstack/react-query-devtools10.00% <ø> (ø)
      @tanstack/react-query-next-experimental∅ <ø> (∅)
      @tanstack/react-query-persist-client100.00% <ø> (ø)
      @tanstack/solid-query78.13% <ø> (ø)
      @tanstack/solid-query-devtools∅ <ø> (∅)
      @tanstack/solid-query-persist-client100.00% <ø> (ø)
      @tanstack/svelte-query87.58% <ø> (ø)
      @tanstack/svelte-query-devtools∅ <ø> (∅)
      @tanstack/svelte-query-persist-client100.00% <ø> (ø)
      @tanstack/vue-query71.10% <ø> (ø)
      @tanstack/vue-query-devtools∅ <ø> (∅)
      :rocket: New features to boost your workflow:
      • :snowflake: Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
      • :package: JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.
  • TkDodo merged this1c8a921

  • TkDodo closed this

  • Sign in to join this conversation.