Skip to content

fix(react): allow using enabled when using useQuery().promise #7

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 14 commits into
base: main
Choose a base branch
from

Conversation

arvi18
Copy link

@arvi18 arvi18 commented Apr 23, 2025

Closes TanStack#8499

Summary by CodeRabbit

  • Tests
    • Added new test cases to verify promise reuse when toggling query enabled state and to ensure correct suspense behavior with dynamic enabled state changes.
  • Refactor
    • Enhanced data fetching logic with refined state checks for more accurate fetch triggering during render.

@arvi18
Copy link
Author

arvi18 commented Apr 23, 2025

View your CI Pipeline Execution ↗ for commit 2f69183.

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

☁️ Nx Cloud last updated this comment at 2025-01-06 18:22:01 UTC

@arvi18
Copy link
Author

arvi18 commented Apr 23, 2025

Open in Stackblitz

More templates

@tanstack/angular-query-devtools-experimental

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

@tanstack/eslint-plugin-query

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

@tanstack/angular-query-experimental

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

@tanstack/query-async-storage-persister

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

@tanstack/query-core

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

@tanstack/query-broadcast-client-experimental

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

@tanstack/query-devtools

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

@tanstack/query-persist-client-core

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

@tanstack/query-sync-storage-persister

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

@tanstack/react-query

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

@tanstack/react-query-devtools

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

@tanstack/react-query-next-experimental

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

@tanstack/react-query-persist-client

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

@tanstack/solid-query

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

@tanstack/solid-query-devtools

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

@tanstack/solid-query-persist-client

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

@tanstack/svelte-query

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

@tanstack/svelte-query-devtools

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

@tanstack/svelte-query-persist-client

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

@tanstack/vue-query

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

@tanstack/vue-query-devtools

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

commit: 2f69183

@arvi18
Copy link
Author

arvi18 commented Apr 23, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 63.04%. Comparing base (6184a89) to head (2f69183).
Report is 9 commits behind head on main.

Additional details and impacted files

Impacted file tree graph

@@             Coverage Diff             @@
##             main    #8501       +/-   ##
===========================================
+ Coverage   46.25%   63.04%   +16.78%     
===========================================
  Files         199      135       -64     
  Lines        7530     4835     -2695     
  Branches     1719     1358      -361     
===========================================
- Hits         3483     3048      -435     
+ Misses       3668     1543     -2125     
+ Partials      379      244      -135     
Components Coverage Δ
@tanstack/angular-query-devtools-experimental ∅ <ø> (∅)
@tanstack/angular-query-experimental 88.65% <ø> (ø)
@tanstack/eslint-plugin-query ∅ <ø> (∅)
@tanstack/query-async-storage-persister 43.85% <ø> (ø)
@tanstack/query-broadcast-client-experimental ∅ <ø> (∅)
@tanstack/query-codemods ∅ <ø> (∅)
@tanstack/query-core 94.15% <ø> (ø)
@tanstack/query-devtools 4.78% <ø> (ø)
@tanstack/query-persist-client-core 57.73% <ø> (ø)
@tanstack/query-sync-storage-persister 84.61% <ø> (ø)
@tanstack/react-query 95.65% <100.00%> (+0.10%) ⬆️
@tanstack/react-query-devtools 10.00% <ø> (ø)
@tanstack/react-query-next-experimental ∅ <ø> (∅)
@tanstack/react-query-persist-client 100.00% <ø> (ø)
@tanstack/solid-query 78.20% <ø> (ø)
@tanstack/solid-query-devtools ∅ <ø> (∅)
@tanstack/solid-query-persist-client 100.00% <ø> (ø)
@tanstack/svelte-query 87.33% <ø> (ø)
@tanstack/svelte-query-devtools ∅ <ø> (∅)
@tanstack/svelte-query-persist-client 100.00% <ø> (ø)
@tanstack/vue-query 71.01% <78.57%> (-0.45%) ⬇️
@tanstack/vue-query-devtools ∅ <ø> (∅)

Copy link

coderabbitai bot commented Apr 23, 2025

Walkthrough

The changes introduce new test cases to both the core and React layers of the query package, focusing on the behavior of queries when toggling the enabled state, especially in relation to promise reuse and React Suspense. Additionally, the logic in useBaseQuery.ts is refactored to more precisely determine when to fetch data optimistically during render, using a detailed inspection of the query cache entry's state rather than a simple presence check. No changes were made to public APIs or exported entity signatures.

Changes

File(s) Change Summary
packages/query-core/src/tests/queryObserver.test.tsx Added a test to verify that switching the enabled state reuses the same promise in QueryObserver.
packages/react-query/src/tests/useQuery.promise.test.tsx Added a test to check correct suspense and fetch behavior when toggling enabled in a Suspense context.
packages/react-query/src/useBaseQuery.ts Refactored logic for deciding when to fetch optimistically during render, using detailed cache state inspection.

Sequence Diagram(s)

sequenceDiagram
    participant Component
    participant useQuery
    participant QueryCache
    participant QueryObserver

    Component->>useQuery: Render with enabled: false
    useQuery->>QueryCache: Check for cache entry
    QueryCache-->>useQuery: Return cache entry (possibly undefined)
    useQuery->>QueryObserver: Subscribe (no fetch)
    Component->>useQuery: Update enabled: true
    useQuery->>QueryCache: Inspect cache entry state
    alt Should fetch (no data or pending/idle)
        useQuery->>QueryCache: fetchOptimistic()
    else Already fetching or data present
        useQuery->>QueryCache: Subscribe to existing promise
    end
    QueryCache-->>useQuery: Promise/data
    useQuery-->>Component: Return data or suspense
Loading

Poem

A toggle of "enabled," a promise reused,
In tests and in code, the logic’s infused.
With Suspense in the mix, the fetch waits its turn,
While cache state is checked with a keener concern.
No changes to exports, just rigor and care—
The queries are smarter, the rabbits aware!
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 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.
    • Generate unit testing code for this file.
    • 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. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • 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 src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

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

Documentation and Community

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

@visz11
Copy link
Collaborator

visz11 commented Apr 23, 2025

@coderabbitai full review

Copy link

coderabbitai bot commented Apr 23, 2025

✅ Actions performed

Full review triggered.

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/react-query/src/useBaseQuery.ts (1)

144-152: Improved granular query fetch control with detailed state inspection.

The code now examines the cache entry's internal state properties instead of simply checking if the entry exists. This allows for more precise control over when to fetch data during render, especially when toggling the enabled flag.

As noted in the comment, this logic might be better placed in getOptimisticResult() in the future. Consider creating a follow-up issue to track this potential refactor if issue TanStack#8507 doesn't already cover it.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4a5990e and 2f69183.

📒 Files selected for processing (3)
  • packages/query-core/src/__tests__/queryObserver.test.tsx (3 hunks)
  • packages/react-query/src/__tests__/useQuery.promise.test.tsx (1 hunks)
  • packages/react-query/src/useBaseQuery.ts (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
packages/query-core/src/__tests__/queryObserver.test.tsx (3)
packages/query-core/src/__tests__/utils.ts (1)
  • queryKey (24-27)
packages/query-core/src/queryObserver.ts (1)
  • QueryObserver (43-759)
packages/query-core/src/thenable.ts (1)
  • pendingThenable (42-82)
packages/react-query/src/useBaseQuery.ts (1)
packages/query-core/src/query.ts (1)
  • promise (193-195)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Test
🔇 Additional comments (4)
packages/react-query/src/useBaseQuery.ts (1)

153-157: Improved conditional query fetching with the new shouldFetch condition.

The code now uses a more precise condition to determine when to fetch data or subscribe to an existing promise. This is particularly important for correctly handling queries when their enabled state changes.

packages/react-query/src/__tests__/useQuery.promise.test.tsx (1)

1381-1447: Well-structured test for enabled state changes with suspense.

This test effectively validates that the enabled flag works correctly with React Suspense:

  1. Initially the query doesn't run when disabled
  2. When enabled, the query shows the loading state
  3. The query function runs exactly once
  4. Data is properly rendered after fetching completes

The test is thorough and directly addresses the issue in the PR title regarding using enabled with useQuery().promise.

packages/query-core/src/__tests__/queryObserver.test.tsx (2)

1-12: Appropriate imports added to support new tests.

The addition of waitFor from @testing-library/dom and pendingThenable from the thenable module provides the necessary utilities for the new test.


1238-1270: Valuable test ensuring promise reuse when toggling enabled state.

This test verifies a critical behavior: when toggling a query from disabled to enabled, the same promise instance should be reused. This is important for React Suspense to work correctly with the promise returned by useQuery().

The test complements the React-level test by verifying the core behavior at the QueryObserver level, ensuring consistent promise handling throughout the library.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Enabling a disabled query does not unsuspend
3 participants