Skip to content

Conversation

arvi18
Copy link

@arvi18 arvi18 commented Apr 23, 2025

let's bring back imperative infinite queries, but only allow them in an all-or-nothing mode, dependent on if getNextPageParam has been passed

Summary by CodeRabbit

  • New Features

    • Added support for explicitly specifying a page parameter when fetching the next or previous page in infinite queries.
  • Bug Fixes

    • Improved handling and safety for optional page parameter functions, reducing potential errors when not provided.
  • Tests

    • Added new tests to verify correct application of page parameters and TypeScript typings for infinite query fetching methods.
  • Refactor

    • Unified and clarified logic for determining fetch direction and page parameters in infinite queries.
  • Documentation

    • Updated TypeScript types to reflect new optional page parameter behavior.

let's bring back imperative infinite queries, but only allow them in an all-or-nothing mode, dependent on if `getNextPageParam` has been passed
@arvi18
Copy link
Author

arvi18 commented Apr 23, 2025

View your CI Pipeline Execution ↗ for commit 644677e.

Command Status Duration Result
nx affected --targets=test:sherif,test:knip,tes... ❌ Failed 2m 9s View ↗
nx run-many --target=build --exclude=examples/*... ❌ Failed 6s View ↗

☁️ Nx Cloud last updated this comment at 2025-02-14 14:45:30 UTC

@arvi18
Copy link
Author

arvi18 commented Apr 23, 2025

Thanks for this! Can we get it merged? It's critical to our use case of using it with AgGrid's serverside row model.

@arvi18
Copy link
Author

arvi18 commented Apr 23, 2025

Hey @TkDodo as @riwu said for us it is also important any update when it will be merged?

@arvi18
Copy link
Author

arvi18 commented Apr 23, 2025

any update for this?

Copy link

coderabbitai bot commented Apr 23, 2025

Walkthrough

This update introduces enhancements to the infinite query logic and its associated type definitions and tests. The primary changes include allowing explicit pageParam values to be passed when fetching the next or previous page in infinite queries, updating the metadata structure to support this, and making the getNextPageParam function optional in the options interface. The observer methods are refactored to accept and forward the pageParam. Tests are added to verify both the runtime behavior and the TypeScript typings for these new capabilities. No breaking changes to public APIs are introduced.

Changes

File(s) Change Summary
packages/query-core/src/infiniteQueryObserver.ts Refactored fetchNextPage and fetchPreviousPage to accept and forward an explicit pageParam in their options, updating their signatures accordingly.
packages/query-core/src/infiniteQueryBehavior.ts Refactored logic to handle explicit pageParam in fetch metadata, unified direction and parameter extraction, and made getNextPageParam optional.
packages/query-core/src/query.ts Extended FetchMeta interface to include an optional pageParam property in fetchMore.
packages/query-core/src/types.ts Made getNextPageParam optional in InfiniteQueryPageParamsOptions interface.
packages/query-core/src/__tests__/infiniteQueryBehavior.test.tsx Added a test verifying that explicit pageParam values are correctly applied and preserved in infinite query behavior.
packages/query-core/src/__tests__/infiniteQueryObserver.test-d.tsx Added type-level tests ensuring correct typing for fetchNextPage and fetchPreviousPage based on the presence of getNextPageParam.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant InfiniteQueryObserver
    participant InfiniteQueryBehavior
    participant Query

    User->>InfiniteQueryObserver: fetchNextPage({ pageParam })
    InfiniteQueryObserver->>Query: fetch({ meta: { fetchMore: { direction: 'forward', pageParam } } })
    Query->>InfiniteQueryBehavior: handle fetchMore with direction and pageParam
    InfiniteQueryBehavior->>Query: Return result with correct page data
    Query->>InfiniteQueryObserver: Resolve fetch promise
    InfiniteQueryObserver->>User: Return updated query result
Loading

Poem

🐇
Pages turn with nimble paws,
Now with params, without a pause.
Forward, backward, hop and fetch—
Infinite queries, no longer a stretch!
Types are checked, the tests are bright,
Rabbit devs rejoice tonight!
🥕✨

✨ 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: 2

📜 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 644677e.

📒 Files selected for processing (6)
  • packages/query-core/src/__tests__/infiniteQueryBehavior.test.tsx (1 hunks)
  • packages/query-core/src/__tests__/infiniteQueryObserver.test-d.tsx (1 hunks)
  • packages/query-core/src/infiniteQueryBehavior.ts (4 hunks)
  • packages/query-core/src/infiniteQueryObserver.ts (1 hunks)
  • packages/query-core/src/query.ts (1 hunks)
  • packages/query-core/src/types.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
packages/query-core/src/__tests__/infiniteQueryBehavior.test.tsx (2)
packages/query-core/src/__tests__/utils.ts (1)
  • queryKey (24-27)
packages/query-core/src/infiniteQueryObserver.ts (1)
  • InfiniteQueryObserver (27-198)
🪛 GitHub Actions: pr
packages/query-core/src/infiniteQueryObserver.ts

[error] 122-122: TypeScript error TS2339: Property 'pageParam' does not exist on type 'FetchNextPageOptions'.

🔇 Additional comments (10)
packages/query-core/src/query.ts (1)

92-92: Looks good! Adding support for explicit pageParam in fetchMore metadata.

This addition to the FetchMeta interface enables passing an explicit pageParam during fetch operations, which is essential for implementing imperative infinite queries. This change works well with the corresponding updates in the infiniteQueryObserver where the fetchNextPage and fetchPreviousPage methods pass this parameter through.

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

274-274: Good change - making getNextPageParam optional aligns with the all-or-nothing imperative mode.

Making getNextPageParam optional is a key change that enables imperative infinite queries. This aligns with the PR objective to support imperative infinite queries in an all-or-nothing mode, where if getNextPageParam is omitted, users must provide explicit page parameters. This also matches the existing optional nature of getPreviousPageParam.

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

76-95: Great type test for the case when getNextPageParam is defined.

This test correctly verifies that when getNextPageParam is provided, the fetchNextPage and fetchPreviousPage methods don't expect or allow a pageParam argument, as it would be calculated by the function. This ensures type safety and prevents confusion in the API.


97-117: Excellent type test for the case when getNextPageParam is missing.

This complementary test ensures that when getNextPageParam is omitted, the fetchNextPage and fetchPreviousPage methods require a pageParam argument. This enforces the all-or-nothing behavior described in the PR objectives and ensures developers can't accidentally omit required parameters.

packages/query-core/src/__tests__/infiniteQueryBehavior.test.tsx (1)

204-306: Well-designed test for imperative infinite queries functionality.

This comprehensive test verifies that explicit pageParam values are correctly applied when fetching pages. It covers the key scenarios:

  1. Initial fetch with the initialPageParam
  2. Fetching next page with explicit pageParam
  3. Fetching previous page with explicit pageParam
  4. Refetching - verifying that manually specified pageParams are preserved

The test provides good coverage of the imperative mode and ensures it works correctly with both new page fetches and refetches. The explicit assertions for each step make the test clear and maintainable.

packages/query-core/src/infiniteQueryBehavior.ts (5)

17-17: Simplified metadata access

Good change to directly access the fetchMore object from the metadata, making the code cleaner and easier to understand.


84-86: Improved condition for fetching next/previous pages

The condition now checks for both fetchMore existence and the presence of old pages, which is more explicit and handles edge cases better. The direction determination is also cleaner, using the fetchMore.direction property directly.


91-95: Support for explicit page parameters

This is the core change that implements the imperative infinite query functionality. The code now checks if an explicit pageParam was provided in fetchMore, and only falls back to using the page parameter functions if it wasn't. This aligns perfectly with the PR objective of supporting explicit page parameters when needed.


103-105: Handling optional getNextPageParam function

This change adds support for cases where getNextPageParam is not provided, falling back to using either the old page parameter or the initial page parameter. This is necessary to make the function optional and support the imperative infinite query mode.


142-148: Added optional chaining for getNextPageParam

Good addition of optional chaining to handle cases where getNextPageParam is undefined. This prevents runtime errors when operating in imperative mode without the parameter functions.

Comment on lines +138 to 150
fetchPreviousPage({
pageParam,
...options
}: FetchPreviousPageOptions = {}): Promise<
InfiniteQueryObserverResult<TData, TError>
> {
return this.fetch({
...options,
meta: {
fetchMore: { direction: 'backward' },
fetchMore: { direction: 'backward', pageParam },
},
})
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Support for explicit pageParam added to fetchPreviousPage

This change mirrors the update to fetchNextPage, adding support for explicit page parameters to the fetchPreviousPage method. This implementation maintains consistency between both pagination directions.

The same type issue applies here - ensure that FetchPreviousPageOptions type is updated to include the pageParam property.

Comment on lines +127 to 136
fetchNextPage({ pageParam, ...options }: FetchNextPageOptions = {}): Promise<
InfiniteQueryObserverResult<TData, TError>
> {
return this.fetch({
...options,
meta: {
fetchMore: { direction: 'forward' },
fetchMore: { direction: 'forward', pageParam },
},
})
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Good update to support imperative infinite queries

The fetchNextPage method now accepts an optional pageParam property which enables users to explicitly control the pagination, aligning with the PR's objective to reintroduce imperative infinite queries functionality.

A small issue to note: the pipeline shows a TypeScript error (TS2339) indicating that 'pageParam' doesn't exist on the FetchNextPageOptions type. The corresponding type definition should be updated.

@atharvsabdeai
Copy link

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

@atharvsabdeai
Copy link

/refacto-test

1 similar comment
@arvi18
Copy link
Author

arvi18 commented Aug 8, 2025

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

Copy link

refacto-test bot commented Aug 8, 2025

No review comments were generated during this review iteration of the PR.

Copy link

refacto-test bot commented Aug 8, 2025

Security Review: Infinite Queries

👍 Well Done
Manual PageParam Support

Enables secure control over pagination parameters.

Type Safety Improvements

Type checking prevents parameter misuse in fetch operations.

📝 Additional Comments
packages/query-core/src/infiniteQueryBehavior.ts (1)
Potential Injection Risk

Unvalidated pageParam flows directly to fetchPage function. If fetchPage uses this parameter in database queries or API calls, it creates potential injection vulnerabilities without proper sanitization.

// Add sanitization function to ensure safe parameter usage
function sanitizePageParam(param: unknown): unknown {
  // Implement appropriate sanitization based on expected usage
  // For example, if numeric:
  if (typeof param === 'string') {
    // Convert to number or sanitize string
    return Number(param) || 0;
  }
  return param;
}

const param =
  fetchMore.pageParam === undefined
    ? pageParamFn(options, oldData)
    : sanitizePageParam(fetchMore.pageParam)

result = await fetchPage(oldData, param, previous)

Standards:

  • CWE-20
  • OWASP-A03

Comment on lines +91 to +94
const param =
fetchMore.pageParam === undefined
? pageParamFn(options, oldData)
: fetchMore.pageParam
Copy link

Choose a reason for hiding this comment

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

Missing PageParam Validation

User-provided pageParam is used without validation. Attackers could inject malicious values causing data exposure or application crashes. Especially risky when pageParam flows to database queries.

Suggested change
const param =
fetchMore.pageParam === undefined
? pageParamFn(options, oldData)
: fetchMore.pageParam
const param =
fetchMore.pageParam === undefined
? pageParamFn(options, oldData)
: validatePageParam(fetchMore.pageParam, options)
// Add this function to validate incoming pageParam values
function validatePageParam(pageParam: unknown, options: InfiniteQueryPageParamsOptions<TData>): unknown {
// Implement validation based on expected pageParam type
// Example: type checking, range validation, sanitization
return pageParam; // Return validated/sanitized value
}
Standards
  • CWE-20
  • OWASP-A03

@visz11
Copy link
Collaborator

visz11 commented Sep 11, 2025

/refacto-test

Copy link

refacto-test bot commented Sep 11, 2025

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

Copy link

refacto-test bot commented Sep 11, 2025

Code Review: InfiniteQuery Enhancement

👍 Well Done
Manual PageParam Support

Added ability to specify custom pageParam for improved control.

Comprehensive Test Coverage

Tests validate new functionality ensuring reliability.

📌 Files Processed
  • packages/query-core/src/tests/infiniteQueryBehavior.test.tsx
  • packages/query-core/src/tests/infiniteQueryObserver.test-d.tsx
  • packages/query-core/src/infiniteQueryBehavior.ts
  • packages/query-core/src/infiniteQueryObserver.ts
  • packages/query-core/src/query.ts
  • packages/query-core/src/types.ts
📝 Additional Comments
packages/query-core/src/infiniteQueryBehavior.ts (4)
Optional Chaining Usage

Using optional chaining (?.) on getNextPageParam is redundant when it's already checked in an if condition. This adds a small runtime overhead. Consider removing the optional chaining since the function is already checked for existence in the condition.

Standards:

  • ISO-IEC-25010-Performance-Time-Behaviour
  • Algorithm-Opt-Redundant-Checks
Conditional Logic Clarity

The ternary operator adds complexity to the parameter selection logic. Consider extracting this into a named helper function to improve readability and maintainability.

Standards:

  • Clean-Code-Functions
  • Clean-Code-Readability
Optional Method Invocation

Using optional chaining for getNextPageParam is a good change but should be consistently applied throughout the codebase. This pattern change might require updates in other locations.

Standards:

  • Clean-Code-Consistency
  • SOLID-OCP
Input Validation Needed

User-provided pageParam is used without validation. Consider adding type checking or validation to prevent unexpected behavior when invalid pageParam values are provided.

Standards:

  • CWE-20
  • OWASP-A04
packages/query-core/src/__tests__/infiniteQueryObserver.test-d.tsx (2)
Incomplete Type Tests

Type tests verify parameter requirements but don't test actual runtime behavior when pageParam is provided with getNextPageParam. This could lead to unexpected behavior when both mechanisms are used together.

Standards:

  • Logic-Verification-TestCoverage
  • Algorithm-Correctness-EdgeCases
  • Business-Rule-Validation
Type Checking Optimization

The new type tests ensure proper TypeScript constraints for pageParam usage. This prevents performance issues at runtime by catching incorrect API usage during development. Good practice for maintaining API integrity and preventing potential runtime errors.

Standards:

  • ISO-IEC-25010-Performance-Resource-Utilization
  • Algorithm-Opt-Type-Safety
packages/query-core/src/infiniteQueryObserver.ts (1)
Documentation Opportunity

Missing JSDoc comments for new pageParam parameter. Could lead to misuse of the API without clear documentation of parameter purpose and usage.

Standards:

  • ISO-IEC-25010-Functional-Appropriateness
  • DbC-Contract-Documentation

Comment on lines +91 to +94
const param =
fetchMore.pageParam === undefined
? pageParamFn(options, oldData)
: fetchMore.pageParam
Copy link

Choose a reason for hiding this comment

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

Missing Null Check

No null check for pageParamFn before invocation. If getNextPageParam/getPreviousPageParam is undefined, this will cause runtime errors when fetchMore.pageParam is undefined.

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

Comment on lines +103 to +104
currentPage === 0 || !options.getNextPageParam
? (oldPageParams[currentPage] ?? options.initialPageParam)
Copy link

Choose a reason for hiding this comment

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

Missing getNextPageParam Check

Logic incorrectly treats missing getNextPageParam as a condition to use oldPageParams instead of calculating next page. This breaks expected behavior for subsequent pages when getNextPageParam is undefined.

Standards
  • Algorithm-Correctness-Conditional
  • Logic-Verification-Flow
  • Business-Rule-Pagination

Comment on lines +142 to 143
? options.getNextPageParam?.(
pages[lastIndex],
Copy link

Choose a reason for hiding this comment

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

Incorrect Optional Chaining

Optional chaining added to getNextPageParam but the function is already checked for existence on line 104. This creates inconsistent logic flow where the function is treated as both optional and required.

Standards
  • Logic-Verification-Consistency
  • Algorithm-Correctness-Nullability
  • Business-Rule-Validation

Comment on lines +127 to 136
fetchNextPage({ pageParam, ...options }: FetchNextPageOptions = {}): Promise<
InfiniteQueryObserverResult<TData, TError>
> {
return this.fetch({
...options,
meta: {
fetchMore: { direction: 'forward' },
fetchMore: { direction: 'forward', pageParam },
},
})
}
Copy link

Choose a reason for hiding this comment

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

Optional Parameter Type

The pageParam parameter is destructured but its type isn't explicitly defined in the function signature. This could lead to maintainability issues when other developers need to understand the expected type.

Standards
  • Clean-Code-Type-Safety
  • Clean-Code-Function-Signatures

* The result will also be used to determine the value of `hasNextPage`.
*/
getNextPageParam: GetNextPageParamFunction<TPageParam, TQueryFnData>
getNextPageParam?: GetNextPageParamFunction<TPageParam, TQueryFnData>
Copy link

Choose a reason for hiding this comment

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

Type Definition Update

Making getNextPageParam optional changes the contract significantly. This requires comprehensive documentation updates and might affect consumers who expect this function to always exist.

Standards
  • SOLID-LSP
  • Clean-Code-Interface-Design

Comment on lines +103 to +104
currentPage === 0 || !options.getNextPageParam
? (oldPageParams[currentPage] ?? options.initialPageParam)
Copy link

Choose a reason for hiding this comment

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

Optional GetNextPageParam Check

The check for !options.getNextPageParam is new but will always be false when refetching since getNextPageParam is used later. This creates an unnecessary condition check on every page fetch. Consider simplifying this logic or adding a comment explaining the purpose of this check for better code clarity.

Standards
  • ISO-IEC-25010-Performance-Time-Behaviour
  • Algorithm-Opt-Conditional-Evaluation

Comment on lines +103 to +104
currentPage === 0 || !options.getNextPageParam
? (oldPageParams[currentPage] ?? options.initialPageParam)
Copy link

Choose a reason for hiding this comment

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

Inconsistent PageParam Logic

Logic change creates inconsistency in pageParam selection. For currentPage=0, oldPageParams[0] was replaced with oldPageParams[currentPage], but for currentPage>0 with getNextPageParam defined, the logic still uses getNextPageParam without considering oldPageParams[currentPage].

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

Comment on lines +138 to +143
fetchPreviousPage({
pageParam,
...options
}: FetchPreviousPageOptions = {}): Promise<
InfiniteQueryObserverResult<TData, TError>
> {
Copy link

Choose a reason for hiding this comment

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

Missing PageParam Validation

fetchPreviousPage accepts pageParam without validation. Invalid pageParam values could cause unexpected behavior or failures during pagination operations.

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

Comment on lines +91 to +94
const param =
fetchMore.pageParam === undefined
? pageParamFn(options, oldData)
: fetchMore.pageParam
Copy link

Choose a reason for hiding this comment

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

Optimize Refetch Logic

The current implementation checks fetchMore.pageParam === undefined to determine whether to use the pageParamFn or the explicit pageParam. This creates unnecessary function calls when pageParam is provided. Consider short-circuit evaluation to avoid calling pageParamFn entirely when pageParam is provided, reducing computational overhead during pagination operations.

Standards
  • ISO-IEC-25010-Performance-Time-Behaviour
  • Algorithm-Opt-Short-Circuit

@visz11
Copy link
Collaborator

visz11 commented Sep 11, 2025

/refacto-test

Copy link

refacto-test bot commented Sep 11, 2025

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

Copy link

refacto-test bot commented Sep 11, 2025

Code Review: Infinite Query Manual PageParam Support

👍 Well Done
Manual PageParam Support

Added support for manual page parameter control enhancing flexibility in pagination.

Comprehensive Test Coverage

Added thorough tests validating the new pageParam functionality across different scenarios.

Type Safety Improvements

Enhanced type checking for fetchNextPage and fetchPreviousPage parameters.

📌 Files Processed
  • packages/query-core/src/tests/infiniteQueryBehavior.test.tsx
  • packages/query-core/src/tests/infiniteQueryObserver.test-d.tsx
  • packages/query-core/src/infiniteQueryBehavior.ts
  • packages/query-core/src/infiniteQueryObserver.ts
  • packages/query-core/src/query.ts
  • packages/query-core/src/types.ts
📝 Additional Comments
packages/query-core/src/__tests__/infiniteQueryBehavior.test.tsx (1)
Unnecessary Refetch Calls

The test confirms that refetch operations trigger separate network calls for each page, which can cause performance issues with many pages. Consider implementing batch refetching or selective page refetching to reduce unnecessary network traffic.

Standards:

  • ISO-IEC-25010-Performance-Resource-Utilization
  • Netflix-Hot-Path-Optimization
packages/query-core/src/infiniteQueryBehavior.ts (1)
Inconsistent Logic Flow

Logic now treats currentPage=0 and missing getNextPageParam identically, but they represent different scenarios. This creates inconsistent behavior where oldPageParams[currentPage] is used even when getNextPageParam is missing but currentPage>0.

Standards:

  • Logic-Verification-Consistency
  • Algorithm-Correctness-Conditional-Logic
  • Business-Rule-Clarity
packages/query-core/src/infiniteQueryObserver.ts (1)
Parameter Destructuring Pattern

The parameter destructuring pattern differs between fetchNextPage and fetchPreviousPage methods. Consistent parameter destructuring would improve code maintainability and readability.

Standards:

  • Clean-Code-Consistency
  • Clean-Code-Method-Design
packages/query-core/src/query.ts (1)
Type Safety Enhancement

Using 'unknown' type for pageParam lacks type safety. Consider stronger typing based on expected parameter format to prevent type-related security issues.

Standards:

  • CWE-20
packages/query-core/src/types.ts (1)
Document Breaking Change

Making getNextPageParam optional is a breaking change. Consider documenting this change clearly to prevent integration failures for consumers.

Standards:

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

* The result will also be used to determine the value of `hasNextPage`.
*/
getNextPageParam: GetNextPageParamFunction<TPageParam, TQueryFnData>
getNextPageParam?: GetNextPageParamFunction<TPageParam, TQueryFnData>
Copy link

Choose a reason for hiding this comment

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

Optional getNextPageParam Without Code Updates

Making getNextPageParam optional without updating all dependent code could cause runtime failures. Some code paths may assume this function exists without checking, leading to potential undefined behavior.

Suggested change
getNextPageParam?: GetNextPageParamFunction<TPageParam, TQueryFnData>
getNextPageParam: GetNextPageParamFunction<TPageParam, TQueryFnData>
Standards
  • ISO-IEC-25010-Reliability-Fault-Tolerance
  • ISO-IEC-25010-Functional-Correctness-Appropriateness

Comment on lines +127 to +143
fetchNextPage({ pageParam, ...options }: FetchNextPageOptions = {}): Promise<
InfiniteQueryObserverResult<TData, TError>
> {
return this.fetch({
...options,
meta: {
fetchMore: { direction: 'forward' },
fetchMore: { direction: 'forward', pageParam },
},
})
}

fetchPreviousPage(
options?: FetchPreviousPageOptions,
): Promise<InfiniteQueryObserverResult<TData, TError>> {
fetchPreviousPage({
pageParam,
...options
}: FetchPreviousPageOptions = {}): Promise<
InfiniteQueryObserverResult<TData, TError>
> {
Copy link

Choose a reason for hiding this comment

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

Missing pageParam Validation

No validation ensures pageParam is provided when getNextPageParam is missing. Without validation, fetchNextPage/fetchPreviousPage could silently pass undefined pageParam when required, causing runtime errors.

Suggested change
fetchNextPage({ pageParam, ...options }: FetchNextPageOptions = {}): Promise<
InfiniteQueryObserverResult<TData, TError>
> {
return this.fetch({
...options,
meta: {
fetchMore: { direction: 'forward' },
fetchMore: { direction: 'forward', pageParam },
},
})
}
fetchPreviousPage(
options?: FetchPreviousPageOptions,
): Promise<InfiniteQueryObserverResult<TData, TError>> {
fetchPreviousPage({
pageParam,
...options
}: FetchPreviousPageOptions = {}): Promise<
InfiniteQueryObserverResult<TData, TError>
> {
fetchNextPage({ pageParam, ...options }: FetchNextPageOptions = {}): Promise<
InfiniteQueryObserverResult<TData, TError>
> {
if (!this.options.getNextPageParam && pageParam === undefined) {
throw new Error('pageParam is required when getNextPageParam is not defined')
}
return this.fetch({
...options,
meta: {
fetchMore: { direction: 'forward', pageParam },
},
})
}
Standards
  • Business-Rule-Validation
  • Logic-Verification-Parameter-Validation
  • Algorithm-Correctness-Input-Validation

Comment on lines +91 to +94
const param =
fetchMore.pageParam === undefined
? pageParamFn(options, oldData)
: fetchMore.pageParam
Copy link

Choose a reason for hiding this comment

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

Input Validation Missing

Manual pageParam is used without validation. Attackers could inject malicious values causing unexpected behavior or data exposure. Add validation before using external pageParam values.

Standards
  • CWE-20
  • OWASP-A03

Comment on lines +142 to 145
? options.getNextPageParam?.(
pages[lastIndex],
pages,
pageParams[lastIndex],
Copy link

Choose a reason for hiding this comment

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

Missing Null Check

Optional chaining on getNextPageParam but no fallback if undefined. Could return undefined when called, potentially causing runtime errors in consumers expecting a value.

Suggested change
? options.getNextPageParam?.(
pages[lastIndex],
pages,
pageParams[lastIndex],
? (options.getNextPageParam?.(
pages[lastIndex],
pages,
pageParams[lastIndex],
) ?? null)
Standards
  • ISO-IEC-25010-Reliability-Fault-Tolerance
  • ISO-IEC-25010-Functional-Correctness-Appropriateness

Comment on lines +91 to +94
const param =
fetchMore.pageParam === undefined
? pageParamFn(options, oldData)
: fetchMore.pageParam
Copy link

Choose a reason for hiding this comment

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

Optional Parameter Type

The pageParam is conditionally used but lacks explicit typing. Adding proper type annotations would improve code clarity and maintainability, especially for future developers working with this API.

Standards
  • Clean-Code-Type-Safety
  • Clean-Code-Explicit-Intent

@visz11
Copy link
Collaborator

visz11 commented Sep 18, 2025

/refacto-test-arvi

Copy link

refacto-visz bot commented Sep 18, 2025

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

@visz11
Copy link
Collaborator

visz11 commented Sep 18, 2025

/refacto-test-arvi

Copy link

refacto-visz bot commented Sep 18, 2025

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

Copy link

refacto-visz bot commented Sep 18, 2025

Code Review: Infinite Queries PageParam Enhancement

👍 Well Done
Comprehensive Test Coverage

Added thorough tests validating the new pageParam functionality for infinite queries.

Type Safety Improvements

Added type tests ensuring proper pageParam behavior in different scenarios.

Manual PageParam Support

Added ability to specify custom pageParam values improving flexibility for complex pagination scenarios.

📌 Files Processed
  • packages/query-core/src/tests/infiniteQueryBehavior.test.tsx
  • packages/query-core/src/tests/infiniteQueryObserver.test-d.tsx
  • packages/query-core/src/infiniteQueryBehavior.ts
  • packages/query-core/src/infiniteQueryObserver.ts
  • packages/query-core/src/query.ts
  • packages/query-core/src/types.ts
📝 Additional Comments
packages/query-core/src/infiniteQueryObserver.ts (3)
Parameter Extraction

The parameter destructuring pattern is inconsistent between fetchNextPage and fetchPreviousPage methods. While both methods now use destructuring, the style and formatting differ slightly. Consistent parameter handling would improve code readability and maintainability.

Standards:

  • Clean-Code-Consistency
  • Maintainability-Quality-Method-Signatures
Validate pageParam Presence

When getNextPageParam is not provided, pageParam becomes mandatory but there's no validation. Consider adding runtime validation to ensure pageParam is provided when required to prevent subtle runtime errors.

Standards:

  • ISO-IEC-25010-Reliability-Fault-Tolerance
  • ISO-IEC-25010-Functional-Correctness-Completeness
Input Validation Needed

The fetchNextPage method accepts an arbitrary pageParam without validation before passing it to the fetch operation. Consider adding validation or sanitization of the pageParam to prevent potential injection vulnerabilities if this parameter is used in sensitive contexts.

Standards:

  • CWE-20
  • OWASP-A03
packages/query-core/src/infiniteQueryBehavior.ts (2)
Explicit Undefined Check

The code checks for strict equality with undefined, but doesn't handle null values which could be passed as pageParam. Consider using a more robust check like (fetchMore.pageParam === undefined || fetchMore.pageParam === null) for complete null safety.

Standards:

  • Algorithm-Correctness-Null-Safety
  • Logic-Verification-Edge-Cases
  • Business-Rule-Input-Validation
Conditional Logic Improvement

The conditional logic has been expanded to handle the case when getNextPageParam is undefined. This creates a more complex condition that mixes different concerns (page index and function existence). Separating these concerns would improve code clarity and maintainability.

Standards:

  • Clean-Code-Simplicity
  • SOLID-SRP

Comment on lines +142 to 145
? options.getNextPageParam?.(
pages[lastIndex],
pages,
pageParams[lastIndex],
Copy link

Choose a reason for hiding this comment

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

Optional getNextPageParam

Making getNextPageParam optional could cause runtime issues if code expects it to be defined. The optional chaining operator allows it to be undefined, but code might still assume a valid function exists.

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

Comment on lines +103 to +104
currentPage === 0 || !options.getNextPageParam
? (oldPageParams[currentPage] ?? options.initialPageParam)
Copy link

Choose a reason for hiding this comment

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

Optional getNextPageParam

The condition checks for missing getNextPageParam but uses oldPageParams[currentPage] which may be undefined. This creates inconsistent parameter handling that could lead to unexpected behavior when refetching pages.

Standards
  • Algorithm-Correctness-Null-Safety
  • Logic-Verification-Control-Flow
  • Business-Rule-State-Consistency

Comment on lines +127 to 135
fetchNextPage({ pageParam, ...options }: FetchNextPageOptions = {}): Promise<
InfiniteQueryObserverResult<TData, TError>
> {
return this.fetch({
...options,
meta: {
fetchMore: { direction: 'forward' },
fetchMore: { direction: 'forward', pageParam },
},
})
Copy link

Choose a reason for hiding this comment

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

Missing Type Validation

The pageParam is passed directly to fetchMore without type validation. Since this is a new parameter that could be undefined, null, or any other value, it should be validated before use to prevent potential type-related issues in the pagination logic.

Standards
  • Business-Rule-Input-Validation
  • Logic-Verification-Data-Flow
  • Algorithm-Correctness-Type-Safety

Comment on lines +91 to +94
const param =
fetchMore.pageParam === undefined
? pageParamFn(options, oldData)
: fetchMore.pageParam
Copy link

Choose a reason for hiding this comment

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

Potential Parameter Override

The implementation allows overriding pageParam with user-provided values without validation. This could potentially lead to injection attacks if pageParam is used in sensitive operations like database queries or file operations without proper validation.

Standards
  • CWE-20
  • OWASP-A03

* The result will also be used to determine the value of `hasNextPage`.
*/
getNextPageParam: GetNextPageParamFunction<TPageParam, TQueryFnData>
getNextPageParam?: GetNextPageParamFunction<TPageParam, TQueryFnData>
Copy link

Choose a reason for hiding this comment

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

Optional getNextPageParam

Making getNextPageParam optional changes the core API contract. This requires careful consideration of backward compatibility and may lead to inconsistent behavior in existing code that expects getNextPageParam to always be defined.

Standards
  • Maintainability-Quality-API-Stability
  • Clean-Code-Interface-Design

Comment on lines +91 to +94
const param =
fetchMore.pageParam === undefined
? pageParamFn(options, oldData)
: fetchMore.pageParam
Copy link

Choose a reason for hiding this comment

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

Conditional Logic Complexity

The nested ternary operator increases cognitive complexity. This pattern could be simplified with a more direct approach like destructuring with defaults or early returns, making the code more readable and maintainable.

Standards
  • Clean-Code-Simplicity
  • Maintainability-Quality-Complexity

@visz11
Copy link
Collaborator

visz11 commented Sep 19, 2025

/refacto-test

Copy link

refacto-test bot commented Sep 19, 2025

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

Copy link

refacto-test bot commented Sep 19, 2025

Code Review: Infinite Query Enhancement

👍 Well Done
Manual PageParam Support

Added support for manual pageParam in fetchNextPage/fetchPreviousPage improving query flexibility.

Comprehensive Test Coverage

Added thorough tests validating new pageParam functionality and refetch behavior.

Type Safety Improvements

Added type tests ensure proper API constraints for better developer experience.

📌 Files Processed
  • packages/query-core/src/tests/infiniteQueryBehavior.test.tsx
  • packages/query-core/src/tests/infiniteQueryObserver.test-d.tsx
  • packages/query-core/src/infiniteQueryBehavior.ts
  • packages/query-core/src/infiniteQueryObserver.ts
  • packages/query-core/src/query.ts
  • packages/query-core/src/types.ts
📝 Additional Comments
packages/query-core/src/types.ts (1)
Optional getNextPageParam

Making getNextPageParam optional allows manual pageParam control but could lead to unexpected behavior if developers forget to provide pageParam when needed. Consider adding runtime validation to ensure either getNextPageParam or pageParam is provided when fetching pages.

Standards:

  • ISO-IEC-25010-Performance-Efficiency-Time-Behavior
  • Optimization-Pattern-Error-Prevention
  • Algorithmic-Complexity-Validation
packages/query-core/src/infiniteQueryBehavior.ts (6)
Consistent Direction Parameter

When refetching pages, all requests use 'forward' direction regardless of their original fetch direction. This could lead to inconsistent behavior if direction affects how data is processed in the queryFn implementation.

Standards:

  • Algorithm-Correctness-Parameter-Consistency
  • Logic-Verification-Data-Flow
Consistent Optional Chaining

The code uses inconsistent patterns for handling optional getNextPageParam. Line 142 uses optional chaining (?.) while line 104 uses a direct null check. Consistent usage of optional chaining would improve reliability.

Standards:

  • ISO-IEC-25010-Reliability-Maturity
  • ISO-IEC-25010-Functional-Correctness-Appropriateness
Conditional Logic Clarity

The conditional expression could be simplified using nullish coalescing operator. Using 'fetchMore.pageParam ?? pageParamFn(options, oldData)' would improve readability and reduce cognitive load when maintaining this code, especially as the conditional logic grows.

Standards:

  • Clean-Code-Simplicity
  • Maintainability-Quality-Readability
Optional Type Handling

The code uses optional chaining (?.) on getNextPageParam which is already checked to be truthy in the condition. This creates redundant null checking that could be simplified for better code clarity and logical consistency.

Standards:

  • Algorithm-Correctness-Conditional-Logic
  • Logic-Verification-Code-Clarity
Conditional Parameter Logic

The conditional parameter logic adds runtime overhead for each page fetch operation. While the overhead is minimal, in high-frequency pagination scenarios this could accumulate. Consider optimizing by checking once if manual mode is being used rather than on every fetch.

Standards:

  • ISO-IEC-25010-Performance-Efficiency-Time-Behavior
  • Optimization-Pattern-Conditional-Evaluation
  • Algorithmic-Complexity-Constant-Time
Manual pageParam Validation

The code accepts any value for fetchMore.pageParam without validation. Consider adding type checking or validation for the pageParam to prevent potential injection of unexpected values that could cause unpredictable behavior in query execution.

Standards:

  • CWE-20
  • OWASP-A03

Comment on lines +103 to +104
currentPage === 0 || !options.getNextPageParam
? (oldPageParams[currentPage] ?? options.initialPageParam)
Copy link

Choose a reason for hiding this comment

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

Incorrect PageParam Selection

The condition incorrectly uses currentPage === 0 OR !options.getNextPageParam, which means even if getNextPageParam is defined, it will still use oldPageParams for the first page. This breaks the expected behavior where getNextPageParam should be used for all pages except the first one.

              currentPage === 0
                ? (oldPageParams[0] ?? options.initialPageParam)
Commitable Suggestion
Suggested change
currentPage === 0 || !options.getNextPageParam
? (oldPageParams[currentPage] ?? options.initialPageParam)
currentPage === 0
? (oldPageParams[0] ?? options.initialPageParam)
Standards
  • Algorithm-Correctness-Conditional-Logic
  • Business-Rule-State-Consistency
  • Logic-Verification-Data-Flow

Comment on lines +142 to 145
? options.getNextPageParam?.(
pages[lastIndex],
pages,
pageParams[lastIndex],
Copy link

Choose a reason for hiding this comment

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

Optional getNextPageParam

The getNextPageParam function is now optional but used without null check at line 105. This could cause runtime errors if getNextPageParam is undefined but the code at line 105 attempts to call it.

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

Comment on lines +84 to +85
if (fetchMore && oldPages.length) {
const previous = fetchMore.direction === 'backward'
Copy link

Choose a reason for hiding this comment

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

Inconsistent Direction Handling

The code now uses fetchMore object but inconsistently handles the direction property. In some places it checks for direction existence, in others it assumes direction is defined. This inconsistency creates maintenance challenges and potential bugs when modifying direction-related logic.

        if (fetchMore?.direction && oldPages.length) {
          const previous = fetchMore.direction === 'backward'
Commitable Suggestion
Suggested change
if (fetchMore && oldPages.length) {
const previous = fetchMore.direction === 'backward'
if (fetchMore?.direction && oldPages.length) {
const previous = fetchMore.direction === 'backward'
Standards
  • Clean-Code-Consistency
  • SOLID-SRP
  • Maintainability-Quality-Predictability

Comment on lines +103 to 106
currentPage === 0 || !options.getNextPageParam
? (oldPageParams[currentPage] ?? options.initialPageParam)
: getNextPageParam(options, result)
if (currentPage > 0 && param == null) {
Copy link

@refacto-test refacto-test bot Sep 19, 2025

Choose a reason for hiding this comment

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

Missing Null Check

The code attempts to call getNextPageParam() at line 104 even when options.getNextPageParam is undefined (checked at line 103). This inconsistency could lead to runtime errors when getNextPageParam is undefined.

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

Comment on lines +127 to +143
fetchNextPage({ pageParam, ...options }: FetchNextPageOptions = {}): Promise<
InfiniteQueryObserverResult<TData, TError>
> {
return this.fetch({
...options,
meta: {
fetchMore: { direction: 'forward' },
fetchMore: { direction: 'forward', pageParam },
},
})
}

fetchPreviousPage(
options?: FetchPreviousPageOptions,
): Promise<InfiniteQueryObserverResult<TData, TError>> {
fetchPreviousPage({
pageParam,
...options
}: FetchPreviousPageOptions = {}): Promise<
InfiniteQueryObserverResult<TData, TError>
> {
Copy link

Choose a reason for hiding this comment

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

Optional Parameter Handling

Inconsistent parameter destructuring patterns between fetchNextPage and fetchPreviousPage methods. The first uses inline destructuring while the second uses multi-line format. This inconsistency makes the code harder to maintain as developers need to mentally parse different patterns.

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

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.

4 participants