Skip to content

Conversation

TkDodo
Copy link
Collaborator

@TkDodo TkDodo commented Aug 18, 2025

Summary by CodeRabbit

  • New Features

    • Added a public CancelledError to surface cancellation outcomes.
  • Bug Fixes

    • Cancelling an initial in-flight fetch now raises CancelledError instead of resolving with missing/undefined data; previous data is preserved when available.
  • Tests

    • Refactored and added tests to validate cancellation behavior, error propagation, and post-cancellation state.

Copy link

coderabbitai bot commented Aug 18, 2025

Walkthrough

Adds a CancelledError export and modifies Query.fetch so canceling an initial (no-data) fetch triggers a CancelledError; tests updated to import CancelledError, simplify cancelQueries to a single key scenario, and add a test asserting imperative fetchQuery rejects with CancelledError.

Changes

Cohort / File(s) Summary of Changes
Core fetch control flow
packages/query-core/src/query.ts
Adjusts cancellation/revert path in Query.fetch: when reverting after cancellation, return existing data only if defined; otherwise set error state and rethrow CancelledError.
Public API exports
packages/query-core/src/index.ts
Adds export class CancelledError extends Error to the package public exports.
Tests
packages/query-core/src/__tests__/queryClient.test.tsx
Imports CancelledError; refactors cancelQueries test to a single-key scenario (pre-populate, start long fetch, cancel, verify previous data returned); adds a test asserting an imperative fetchQuery rejects with CancelledError for an initial fetch cancellation.

Sequence Diagram(s)

sequenceDiagram
  participant Test as Test
  participant Client as QueryClient
  participant Cache as QueryCache
  participant Query as Query

  Test->>Client: fetchQuery(key, fn) -> Promise
  Client->>Cache: get/create Query
  Cache->>Query: fetch()
  Note right of Query: fetch starts (initial/no data)

  Test->>Client: cancelQueries(key)
  Client->>Query: cancel()
  Query->>Query: revert state to previous
  alt previous data exists
    Query-->>Client: resolve(existing data) and return data
  else no previous data (initial fetch)
    Query->>Client: set error = CancelledError
    Query-->>Client: throw CancelledError (promise rejects)
  end

  Test-->>Test: expect promise to reject instanceOf CancelledError
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

A rabbit taps the keyboard light and skips a beat,
I cancel mid-hop when fetch and timeout meet.
If old crumbs remain, we nibble what’s known,
If none, a CancelledError hops out and is shown.
Little paws, quick fix — then back to the meadow I beat. 🐇✨

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.


📜 Recent 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 763fb7f and 06e178f.

📒 Files selected for processing (1)
  • packages/query-core/src/__tests__/queryClient.test.tsx (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/query-core/src/tests/queryClient.test.tsx
⏰ 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
✨ 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/fix/initial-query-cancellation

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

Copy link

nx-cloud bot commented Aug 18, 2025

View your CI Pipeline Execution ↗ for commit 06e178f

Command Status Duration Result
nx affected --targets=test:sherif,test:knip,tes... ✅ Succeeded 3m 36s View ↗
nx run-many --target=build --exclude=examples/*... ✅ Succeeded 1m 19s View ↗

☁️ Nx Cloud last updated this comment at 2025-08-19 09:01:29 UTC

Copy link

pkg-pr-new bot commented Aug 18, 2025

More templates

@tanstack/angular-query-devtools-experimental

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

@tanstack/angular-query-experimental

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

@tanstack/eslint-plugin-query

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

@tanstack/query-async-storage-persister

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

@tanstack/query-broadcast-client-experimental

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

@tanstack/query-core

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

@tanstack/query-devtools

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

@tanstack/query-persist-client-core

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

@tanstack/query-sync-storage-persister

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

@tanstack/react-query

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

@tanstack/react-query-devtools

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

@tanstack/react-query-next-experimental

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

@tanstack/react-query-persist-client

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

@tanstack/solid-query

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

@tanstack/solid-query-devtools

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

@tanstack/solid-query-persist-client

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

@tanstack/svelte-query

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

@tanstack/svelte-query-devtools

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

@tanstack/svelte-query-persist-client

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

@tanstack/vue-query

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

@tanstack/vue-query-devtools

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

commit: 06e178f

Copy link

github-actions bot commented Aug 18, 2025

Sizes for commit 06e178f:

Branch Bundle Size
Main
This PR

Copy link

@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 (2)
packages/query-core/src/__tests__/queryClient.test.tsx (1)

1065-1081: Great addition: asserts cancel-on-initial-fetch rejects with CancelledError

This directly guards against regressing to “resolve with undefined” on cancellation. Consider strengthening the test by also asserting the resulting query state transitions to error with a CancelledError.

Apply this diff to extend the assertions:

       await queryClient.cancelQueries({ queryKey: key })

-      await expect(promise).rejects.toBeInstanceOf(CancelledError)
+      await expect(promise).rejects.toBeInstanceOf(CancelledError)
+      const state = queryClient.getQueryState(key)
+      expect(state?.status).toBe('error')
+      expect(state?.fetchStatus).toBe('idle')
+      expect(state?.data).toBeUndefined()
+      expect(state?.error).toBeInstanceOf(CancelledError)
     })
packages/query-core/src/query.ts (1)

561-565: Minor clarity: read from revert snapshot instead of mutable state

You’ve just restored state from #revertState; checking the snapshot directly makes the intent explicit and decouples the return value from any subsequent state churn.

Apply this small refactor:

-          if (this.state.data !== undefined) {
-            return this.state.data
-          }
+          const revertedData = this.#revertState?.data
+          if (revertedData !== undefined) {
+            return revertedData
+          }
📜 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 f1e608b and c77c133.

📒 Files selected for processing (2)
  • packages/query-core/src/__tests__/queryClient.test.tsx (2 hunks)
  • packages/query-core/src/query.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
packages/query-core/src/__tests__/queryClient.test.tsx (3)
packages/query-core/src/query.ts (1)
  • promise (198-200)
packages/query-core/src/utils.ts (1)
  • sleep (355-359)
packages/query-core/src/retryer.ts (1)
  • CancelledError (58-66)
⏰ 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 (2)
packages/query-core/src/__tests__/queryClient.test.tsx (1)

4-4: Verified public API export of CancelledError

  • Defined in packages/query-core/src/retryer.ts (line 58)
  • Re-exported in packages/query-core/src/index.ts (line 3)

You can safely import CancelledError from the package root in your tests.

packages/query-core/src/query.ts (1)

561-565: Fix is correct: don’t revert to undefined data on cancel of initial fetch

Behavior now reverts only if there’s prior data; otherwise it enters the error path and rethrows CancelledError. This matches the intended contract for initial fetch cancellation and prevents accidental resolution with undefined.

@TkDodo TkDodo closed this Aug 18, 2025
@TkDodo TkDodo reopened this Aug 19, 2025
Comment on lines -561 to +566
return this.state.data!
// if the initial fetch was cancelled, we have no data, so we have
// to get reject with a CancelledError
if (this.state.data === undefined) {
throw error
}
return this.state.data
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

this changes makes sure we never resolve with undefined for imperative methods like queryClient.fetchQuery(...). The bang operator ! was a dead giveaway that this could happen 😅

Copy link

codecov bot commented Aug 19, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 59.26%. Comparing base (2989e69) to head (06e178f).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files

Impacted file tree graph

@@             Coverage Diff             @@
##             main    #9577       +/-   ##
===========================================
+ Coverage   45.15%   59.26%   +14.11%     
===========================================
  Files         208      137       -71     
  Lines        8318     5558     -2760     
  Branches     1875     1489      -386     
===========================================
- Hits         3756     3294      -462     
+ Misses       4115     1960     -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.57% <100.00%> (+<0.01%) ⬆️
@tanstack/query-devtools 3.48% <ø> (ø)
@tanstack/query-persist-client-core 79.47% <ø> (ø)
@tanstack/query-sync-storage-persister 84.61% <ø> (ø)
@tanstack/query-test-utils ∅ <ø> (∅)
@tanstack/react-query 95.95% <ø> (ø)
@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.

Copy link

@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 (1)
packages/query-core/src/__tests__/queryClient.test.tsx (1)

997-1013: Make the pending fetch explicit to avoid potential unhandled rejections and assert the new behavior.
Today this is fine, but if cancel semantics regress to a rejection in the “has data” case, this could turn into an unhandled rejection. Capturing the Promise lets us assert it resolves to previous data after revert.

Apply:

-      void queryClient.fetchQuery({
+      const pending = queryClient.fetchQuery({
         queryKey: key1,
         queryFn: () => sleep(1000).then(() => 'data2'),
       })
 
       await vi.advanceTimersByTimeAsync(10)
 
       await queryClient.cancelQueries()
 
+      // with previous data present, imperative fetch should resolve to that data after cancel
+      await expect(pending).resolves.toBe('data')
+
       const state1 = queryClient.getQueryState(key1)
       expect(state1).toMatchObject({
         data: 'data',
         status: 'success',
       })
📜 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 c77c133 and 763fb7f.

📒 Files selected for processing (2)
  • packages/query-core/src/__tests__/queryClient.test.tsx (3 hunks)
  • packages/query-core/src/query.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/query-core/src/query.ts
🧰 Additional context used
🧬 Code Graph Analysis (1)
packages/query-core/src/__tests__/queryClient.test.tsx (2)
packages/query-core/src/utils.ts (1)
  • sleep (355-359)
packages/query-core/src/retryer.ts (1)
  • CancelledError (58-66)
⏰ 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). (3)
  • GitHub Check: autofix
  • GitHub Check: Test
  • GitHub Check: Preview
🔇 Additional comments (2)
packages/query-core/src/__tests__/queryClient.test.tsx (2)

4-4: Importing CancelledError for instance checks looks right; verify re-export path.
Assuming CancelledError is re-exported from the package root (..), this keeps tests aligned with the public API surface. If it isn't re-exported, switch the import to its source module to avoid instanceof mismatches.


1033-1059: Solid regression test for cancelled initial fetch -> CancelledError and reverted state.
Asserts both rejection type and final state (pending/idle/no data/no error). This aligns with the intended “never revert to undefined data” behavior for initial fetches.

@TkDodo TkDodo merged commit e4f5ce8 into main Aug 19, 2025
8 checks passed
@TkDodo TkDodo deleted the feature/fix/initial-query-cancellation branch August 19, 2025 09:09
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