Skip to content

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

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 ∅ <ø> (∅)

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

@coderabbitai
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.

@atharvsabdeai
Copy link

/refacto-test

@refacto-test
Copy link

refacto-test bot commented Jul 23, 2025

Refacto is reviewing this PR. Please wait for the review comments to be posted.

willFetch(result, isRestoring)
) {
const promise = isNewCacheEntry
// This fetching in the render should likely be done as part of the getOptimisticResult() considering https://github.com/TanStack/query/issues/8507
Copy link

Choose a reason for hiding this comment

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

Logic Issue: The condition for shouldFetch has been modified to check cache entry state, but the comment "This fetching in the render should likely be done as part of the getOptimisticResult() considering TanStack#8507" suggests this may be a temporary solution. Consider addressing this architectural improvement in a future PR to ensure proper separation of concerns and better maintainability.

@arvi18
Copy link
Author

arvi18 commented Aug 8, 2025

/refacto-test

@refacto-test
Copy link

refacto-test bot commented Aug 8, 2025

Refacto is reviewing this PR. Please wait for the review comments to be posted.

@refacto-test
Copy link

refacto-test bot commented Aug 8, 2025

Security Review: Query Promise

👍 Well Done
Consistent Promise Reuse

Maintains single promise instance across enabled state changes.

📝 Additional Comments
packages/react-query/src/**tests**/useQuery.promise.test.tsx (1)
Missing Error Handling

Test lacks error path validation. Error handling gaps in promise resolution could lead to unhandled rejections. Potential for silent failures in production.

it('should handle errors with suspense when enabled changes', async () => {
 const key = queryKey()
 const renderStream = createRenderStream({ snapshotDOM: true })
 const testError = new Error('test error')
 const queryFn = vi.fn(async () => {
 await sleep(1)
 throw testError
 })

 function MyComponent(props: { enabled: boolean }) {
 const query = useQuery({
 queryKey: key,
 queryFn,
 enabled: props.enabled,
 retry: false
 })

 try {
 const data = React.use(query.promise)
 return <>{data}</>
 } catch (error) {
 return <>error: {error.message}</>
 }
 }

 function ErrorBoundary({ children }) {
 return (
 <React.ErrorBoundary fallback={<div>Error boundary triggered</div>}>
 {children}
 </React.ErrorBoundary>
 )
 }

 function Loading() {
 return <>loading..</>
 }

 function Page() {
 const [enabled, setEnabled] = React.useState(false)

 return (
 <div>
 <button onClick={() => setEnabled(true)}>enable</button>
 <ErrorBoundary>
 <React.Suspense fallback={<Loading />}>
 <MyComponent enabled={enabled} />
 </React.Suspense>
 </ErrorBoundary>
 </div>
 )
 }

 const rendered = await renderStream.render(
 <QueryClientProvider client={queryClient}>
 <Page />
 </QueryClientProvider>,
 )

 {
 const result = await renderStream.takeRender()
 result.withinDOM().getByText('loading..')
 }

 expect(queryFn).toHaveBeenCalledTimes(0)
 rendered.getByText('enable').click()

 {
 const result = await renderStream.takeRender()
 result.withinDOM().getByText('loading..')
 }

 expect(queryFn).toHaveBeenCalledTimes(1)

 {
 const result = await renderStream.takeRender()
 result.withinDOM().getByText('error: test error')
 }

 expect(queryFn).toHaveBeenCalledTimes(1)
})

Standards:

  • CWE-755
  • OWASP-A04

Comment on lines +144 to +147
// This fetching in the render should likely be done as part of the getOptimisticResult() considering https://github.com/TanStack/query/issues/8507
const state = cacheEntry?.state

const shouldFetch =
Copy link

Choose a reason for hiding this comment

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

Race Condition Risk

Insufficient state validation creates race condition when enabled changes. Concurrent renders could trigger multiple fetches with inconsistent state. Potential memory leaks and unpredictable component behavior.

Suggested change
// This fetching in the render should likely be done as part of the getOptimisticResult() considering https://github.com/TanStack/query/issues/8507
const state = cacheEntry?.state
const shouldFetch =
const promise = shouldFetch
? // Fetch immediately on render in order to ensure `.promise` is resolved even if the component is unmounted
fetchOptimistic(defaultedOptions, observer, errorResetBoundary)
: // subscribe to the "cache promise" so that we can finalize the currentThenable once data comes in
observer.getOptimisticResult(defaultedOptions).promise
Standards
  • CWE-362
  • OWASP-A06

@coderabbit-test coderabbit-test deleted a comment from refacto-test bot Aug 8, 2025
@coderabbit-test coderabbit-test deleted a comment from refacto-test bot Aug 8, 2025
@visz11
Copy link
Collaborator

visz11 commented Sep 17, 2025

/refacto-test-arvi

@refacto-visz
Copy link

refacto-visz bot commented Sep 17, 2025

Refacto is reviewing this PR. Please wait for the review comments to be posted.

@refacto-visz
Copy link

refacto-visz bot commented Sep 17, 2025

Code Review: Promise Handling in React Query

👍 Well Done
Promise Reuse

Reusing the same promise when switching enabled state prevents unnecessary promise churn.

Comprehensive Testing

Added thorough test coverage for enabled state changes with suspense.

📌 Files Processed
  • packages/react-query/src/tests/useQuery.promise.test.tsx
  • packages/query-core/src/tests/queryObserver.test.tsx
  • packages/react-query/src/useBaseQuery.ts
📝 Additional Comments
packages/react-query/src/useBaseQuery.ts (1)
Clarify Fetch Comment

The comment suggests this render-time fetching should be moved to getOptimisticResult(), but doesn't indicate when this will happen. Adding a TODO or clarifying the timeline would help prevent this optimization from being forgotten.

Standards:

  • ISO-IEC-25010-Reliability-Maturity
  • SRE-Documentation

Comment on lines +144 to +153
// This fetching in the render should likely be done as part of the getOptimisticResult() considering https://github.com/TanStack/query/issues/8507
const state = cacheEntry?.state

const shouldFetch =
!state ||
(state.data === undefined &&
state.status === 'pending' &&
state.fetchStatus === 'idle')

const promise = shouldFetch
Copy link

Choose a reason for hiding this comment

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

Inconsistent Fetch Condition

The condition for fetching changed from 'isNewCacheEntry' to 'shouldFetch', but the variable 'isNewCacheEntry' is no longer used. This creates inconsistency between variable declaration and usage, potentially causing unexpected behavior when the enabled state changes.

Standards
  • ISO-IEC-25010-Reliability-Maturity
  • ISO-IEC-25010-Functional-Correctness-Appropriateness

@visz11
Copy link
Collaborator

visz11 commented Sep 18, 2025

/refacto-test-arvi

@refacto-visz
Copy link

refacto-visz bot commented Sep 18, 2025

Refacto is reviewing this PR. Please wait for the review comments to be posted.

1 similar comment
@refacto-test
Copy link

refacto-test bot commented Sep 18, 2025

Refacto is reviewing this PR. Please wait for the review comments to be posted.

@refacto-test
Copy link

refacto-test bot commented Sep 18, 2025

Code Review: React Query Promise Handling

👍 Well Done
Promise Reuse Implementation

Improved reliability by ensuring consistent promise reference across enabled state changes.

Comprehensive Test Coverage

Added thorough test case validating enabled state changes with suspense functionality.

📌 Files Processed
  • packages/react-query/src/tests/useQuery.promise.test.tsx
  • packages/query-core/src/tests/queryObserver.test.tsx
  • packages/react-query/src/useBaseQuery.ts
📝 Additional Comments
packages/react-query/src/useBaseQuery.ts (8)
Memoize Fetch Condition

The shouldFetch condition is recalculated on each render. For components that render frequently, memoizing this calculation would prevent unnecessary recalculations. This would improve render performance in high-frequency update scenarios.

Standards:

  • ISO-IEC-25010-Performance-Efficiency-Resource-Utilization
  • Optimization-Pattern-Memoization
  • React-Performance-Render-Optimization
Missing Comment Update

The comment above the conditional fetch is now outdated. It still refers to fetching immediately on render, but the condition has changed from isNewCacheEntry to shouldFetch with different logic. The comment should be updated to reflect the new condition's purpose.

Standards:

  • Logic-Verification-Documentation
  • Business-Rule-Code-Clarity
Clarify Fetch Logic

The comment mentions this logic should be part of getOptimisticResult(), but the implementation remains in the current function. This creates a logical inconsistency between the comment's suggestion and the actual implementation, potentially causing confusion for future maintainers.

Standards:

  • Business-Rule-Code-Organization
  • Logic-Verification-Implementation
Variable Naming Clarity

The variable name 'shouldFetch' doesn't fully capture the complex condition it represents. A more descriptive name like 'isNewOrPendingIdleQuery' would better communicate the intent and conditions being checked.

Standards:

  • Clean-Code-Meaningful-Names
  • Maintainability-Quality-Readability
Extract Complex Condition

The complex condition for shouldFetch combines multiple checks that represent a specific query state. Extracting this logic into a helper function like 'isPendingIdleQuery(state)' would improve readability and make the intent clearer.

Standards:

  • Clean-Code-Functions
  • SOLID-SRP
  • Maintainability-Quality-Complexity
Variable Name Improvement

The variable name change from 'isNewCacheEntry' to 'cacheEntry' improves clarity by representing what the variable actually contains (the entry itself) rather than a boolean derived from it. This makes the code more maintainable.

Standards:

  • Clean-Code-Meaningful-Names
  • Maintainability-Quality-Readability
Potential Memory Leak

The new shouldFetch condition could potentially create unnecessary promises when state transitions occur. This might lead to memory leaks if promises aren't properly garbage collected during rapid state changes. Consider implementing a promise cache cleanup mechanism for long-running applications.

Standards:

  • CWE-401
  • OWASP-A06
Improve Code Comment

The comment indicates this render-time fetching should be moved to getOptimisticResult(). While correct, the comment doesn't explain reliability implications. Fetching during render can cause performance issues and potential race conditions that affect system stability.

Standards:

  • ISO-IEC-25010-Reliability-Maturity
  • DbC-Documentation
packages/query-core/src/__tests__/queryObserver.test.tsx (1)
Promise Race Condition

The test introduces a potential race condition where success.resolve() might be called multiple times if multiple success events occur. While not exploitable in this test context, similar patterns in production code could lead to unpredictable behavior in promise resolution chains.

Standards:

  • CWE-362
  • OWASP-A10

Comment on lines +147 to +151
const shouldFetch =
!state ||
(state.data === undefined &&
state.status === 'pending' &&
state.fetchStatus === 'idle')
Copy link

Choose a reason for hiding this comment

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

Incorrect Fetch Condition

The fetch condition logic has been changed from a simple cache entry check to a more complex state-based condition. However, the new condition will trigger a fetch when state.data is undefined AND status is pending AND fetchStatus is idle, which is too restrictive and may prevent necessary fetches in other valid scenarios.

    const shouldFetch =
      !state ||
      (state.data === undefined &&
        (state.status !== 'success' || state.fetchStatus === 'idle'))
Commitable Suggestion
Suggested change
const shouldFetch =
!state ||
(state.data === undefined &&
state.status === 'pending' &&
state.fetchStatus === 'idle')
const shouldFetch =, !state ||, (state.data === undefined &&, (state.status !== 'success' || state.fetchStatus === 'idle'))
Standards
  • Algorithm-Correctness-Conditional-Logic
  • Business-Rule-State-Management
  • Logic-Verification-Data-Flow

Comment on lines +147 to +151
const shouldFetch =
!state ||
(state.data === undefined &&
state.status === 'pending' &&
state.fetchStatus === 'idle')
Copy link

Choose a reason for hiding this comment

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

Inconsistent Fetch Condition

The shouldFetch condition doesn't account for enabled state changes. When enabled changes from false to true, the condition may not trigger a fetch if state exists with pending status, causing stale or missing data. This creates inconsistent behavior when toggling enabled state.

Standards
  • ISO-IEC-25010-Reliability-Maturity
  • ISO-IEC-25010-Functional-Correctness-Appropriateness
  • SRE-Predictable-Behavior

Comment on lines +147 to +151
const shouldFetch =
!state ||
(state.data === undefined &&
state.status === 'pending' &&
state.fetchStatus === 'idle')
Copy link

Choose a reason for hiding this comment

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

Redundant State Check

The condition checks for !state first, then accesses state properties without null check in the second condition. If state is null/undefined, the second condition would cause runtime errors. This creates potential for uncaught exceptions during state transitions.

Standards
  • ISO-IEC-25010-Reliability-Fault-Tolerance
  • ISO-IEC-25010-Functional-Correctness-Appropriateness
  • DbC-Preconditions

Comment on lines +147 to +151
const shouldFetch =
!state ||
(state.data === undefined &&
state.status === 'pending' &&
state.fetchStatus === 'idle')
Copy link

Choose a reason for hiding this comment

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

Redundant State Check

The shouldFetch condition performs redundant checks that could be simplified. When state is undefined (!state), the subsequent condition is unnecessary. This creates extra boolean operations on every render affecting component performance under high frequency renders.

Standards
  • ISO-IEC-25010-Performance-Efficiency-Time-Behavior
  • Optimization-Pattern-Conditional-Logic
  • Algorithmic-Complexity-Boolean-Logic

willFetch(result, isRestoring)
) {
const promise = isNewCacheEntry
// This fetching in the render should likely be done as part of the getOptimisticResult() considering https://github.com/TanStack/query/issues/8507
Copy link

Choose a reason for hiding this comment

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

Inline Comment Placement

The comment is placed directly before the implementation logic it describes, breaking the flow of code. Moving this comment above the entire block (before line 143) would improve readability while maintaining the context.

Standards
  • Clean-Code-Comments
  • Maintainability-Quality-Readability

@refacto-test
Copy link

refacto-test bot commented Sep 18, 2025

Refacto is reviewing this PR. Please wait for the review comments to be posted.

@refacto-test
Copy link

refacto-test bot commented Sep 18, 2025

Code Review: React Query Promise Handling

👍 Well Done
Consistent Promise Reuse

Ensuring same promise is reused when enabled state changes improves reliability and prevents unnecessary suspense fallbacks.

Comprehensive Test Coverage

Added test case verifies enabled state changes work correctly with suspense.

📌 Files Processed
  • packages/react-query/src/tests/useQuery.promise.test.tsx
  • packages/query-core/src/tests/queryObserver.test.tsx
  • packages/react-query/src/useBaseQuery.ts
📝 Additional Comments
packages/react-query/src/useBaseQuery.ts (6)
Extract Condition Logic

Complex condition logic could be extracted to a named function like 'shouldFetchData(state)'. This would improve readability and make the intent clearer, especially as this appears to be a core decision point.

Standards:

  • Clean-Code-Functions
  • Maintainability-Quality-Complexity
Conditional Fetch Optimization

The new shouldFetch condition is more specific but still performs multiple property checks on each render. Consider extracting this logic into a memoized helper function to avoid redundant condition evaluations in hot render paths, especially for components with frequent re-renders.

Standards:

  • ISO-IEC-25010-Performance-Efficiency-Time-Behavior
  • Optimization-Pattern-Memoization
Improve Code Comment

The comment indicates this fetching logic should be moved to getOptimisticResult(). Implementing this suggestion would improve code organization and reliability by centralizing fetch decision logic in a more appropriate location.

Standards:

  • ISO-IEC-25010-Reliability-Maturity
  • ISO-IEC-25010-Functional-Correctness-Appropriateness
Clarify Fetch Condition

The comment indicates this render-time fetching should be moved to getOptimisticResult(). This architectural decision is correct but left as a TODO comment rather than being implemented, creating potential for future logical inconsistency if the issue is forgotten.

Standards:

  • Algorithm-Correctness-Component-Design
  • Logic-Verification-Architecture
Variable Naming Improvement

Renaming from 'isNewCacheEntry' to 'cacheEntry' improves clarity but loses the original boolean intent. Consider using both variables for maximum clarity: 'const cacheEntry = ...; const isNewCacheEntry = !cacheEntry;'

Standards:

  • Clean-Code-Names
  • Maintainability-Quality-Readability
Unnecessary Fetch Optimization

The new shouldFetch condition adds complexity but may create race conditions during state transitions. Consider implementing this optimization in getOptimisticResult() as suggested in the comment to prevent potential timing issues with promise resolution.

Standards:

  • CWE-362
  • OWASP-A06

Comment on lines +147 to +151
const shouldFetch =
!state ||
(state.data === undefined &&
state.status === 'pending' &&
state.fetchStatus === 'idle')
Copy link

Choose a reason for hiding this comment

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

Unnecessary Fetch Condition

The shouldFetch condition checks for pending status but idle fetchStatus, which is contradictory. This could cause unnecessary fetches or missed fetches in edge cases, affecting query reliability and causing inconsistent behavior.

Standards
  • ISO-IEC-25010-Reliability-Maturity
  • ISO-IEC-25010-Functional-Correctness-Appropriateness

Comment on lines +144 to +151
// This fetching in the render should likely be done as part of the getOptimisticResult() considering https://github.com/TanStack/query/issues/8507
const state = cacheEntry?.state

const shouldFetch =
!state ||
(state.data === undefined &&
state.status === 'pending' &&
state.fetchStatus === 'idle')
Copy link

Choose a reason for hiding this comment

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

Incorrect Fetch Condition

The original condition used isNewCacheEntry to determine fetching, but the new logic checks state properties. This creates a logical inconsistency where a query with pending status but non-idle fetchStatus would be incorrectly skipped, potentially causing stale data to be used.

Standards
  • Algorithm-Correctness-Conditional-Logic
  • Business-Rule-State-Consistency

Comment on lines +1431 to +1438
expect(queryFn).toHaveBeenCalledTimes(0)
rendered.getByText('enable').click()

{
const result = await renderStream.takeRender()
result.withinDOM().getByText('loading..')
}

Copy link

Choose a reason for hiding this comment

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

Incomplete Test Coverage

The test verifies queryFn is called exactly once, but doesn't test the case where enabled changes from true to false and back to true. This leaves a logical gap in test coverage since the promise reuse behavior isn't fully verified across multiple enabled state transitions.

Standards
  • Algorithm-Correctness-Test-Coverage
  • Logic-Verification-Edge-Cases

willFetch(result, isRestoring)
) {
const promise = isNewCacheEntry
// This fetching in the render should likely be done as part of the getOptimisticResult() considering https://github.com/TanStack/query/issues/8507
Copy link

Choose a reason for hiding this comment

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

Inline Comment Clarity

The comment indicates a potential architectural improvement but doesn't explain why the current implementation is problematic. Adding context about the architectural concern would improve future maintainability when revisiting this code.

Standards
  • Clean-Code-Comments
  • Maintainability-Quality-Documentation

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

4 participants