Repository navigation
fix(react-query): always inject cursor field in infinite queries - #7361
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
Walkthrough
Pre-merge checks:
|
There was a problem hiding this comment.
π§Ή Nitpick comments (3)
packages/react-query/test/regression/issue-6862-infinite-query-cursor-initial-load.test.tsx (3)
1-5: Drop unusedPostimport and the unneededReactdefault import.
Postis imported but never referenced. Per the coding guidelines, the JSX runtime is used in this repo, soReactdoes not need to be imported for JSX β onlyFragmentis needed here.β»οΈ Proposed cleanup
-import type { Post } from '../__testHelpers'; import { createAppRouter } from '../__testHelpers'; import { render } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; -import React, { Fragment } from 'react'; +import { Fragment } from 'react';As per coding guidelines: "Use the JSX runtime (no need to import React for JSX)".
π€ Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/react-query/test/regression/issue-6862-infinite-query-cursor-initial-load.test.tsx` around lines 1 - 5, Remove the unused type import Post and the unnecessary default React import from the top of the test file; keep the named Fragment import (used in JSX) and ensure only needed imports remain (e.g., retain Fragment, createAppRouter, render, userEvent) so the file uses the JSX runtime without importing React.
60-67: Redundant assertion aftervi.waitFor.Line 66 re-asserts the same condition that already passed inside
vi.waitFor. It can be removed for clarity.β»οΈ Proposed cleanup
// Wait for initial load to complete - this would fail if cursor was not injected await vi.waitFor(() => { expect(utils.container).toHaveTextContent('first post'); }); - - // Verify the data loaded successfully - expect(utils.container).toHaveTextContent('first post'); });π€ Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/react-query/test/regression/issue-6862-infinite-query-cursor-initial-load.test.tsx` around lines 60 - 67, Remove the redundant assertion that repeats the condition already checked inside vi.waitFor: delete the second expect(utils.container).toHaveTextContent('first post') that follows the vi.waitFor block so the test relies on the waitFor assertion only (leave the vi.waitFor(...) { expect(utils.container).toHaveTextContent('first post') } intact).
24-120: Consider deduplicating the two tests.The two tests share the same component scaffolding and only differ by the refetch trigger. Extracting a shared
MyComponent(or a helper that renders + waits for initial load) would reduce duplication and make future maintenance easier. Not blocking.π€ Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/react-query/test/regression/issue-6862-infinite-query-cursor-initial-load.test.tsx` around lines 24 - 120, Both tests duplicate the same MyComponent and render/wait logic; extract a single reusable component or render helper to reduce duplication by creating a shared MyComponent (or a renderAndWait helper) that uses trpc.paginatedPosts.useInfiniteQuery with the same args and exposes the refetch trigger (data-testid="refetch") when needed, then have the two tests call that shared renderer: one just asserts initial load, the other clicks the refetch button and asserts again; update references to utils/container and userEvent.click to use the returned utilities from the shared render helper so both tests reuse the same scaffolding.
π€ Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In
`@packages/react-query/test/regression/issue-6862-infinite-query-cursor-initial-load.test.tsx`:
- Around line 1-5: Remove the unused type import Post and the unnecessary
default React import from the top of the test file; keep the named Fragment
import (used in JSX) and ensure only needed imports remain (e.g., retain
Fragment, createAppRouter, render, userEvent) so the file uses the JSX runtime
without importing React.
- Around line 60-67: Remove the redundant assertion that repeats the condition
already checked inside vi.waitFor: delete the second
expect(utils.container).toHaveTextContent('first post') that follows the
vi.waitFor block so the test relies on the waitFor assertion only (leave the
vi.waitFor(...) { expect(utils.container).toHaveTextContent('first post') }
intact).
- Around line 24-120: Both tests duplicate the same MyComponent and render/wait
logic; extract a single reusable component or render helper to reduce
duplication by creating a shared MyComponent (or a renderAndWait helper) that
uses trpc.paginatedPosts.useInfiniteQuery with the same args and exposes the
refetch trigger (data-testid="refetch") when needed, then have the two tests
call that shared renderer: one just asserts initial load, the other clicks the
refetch button and asserts again; update references to utils/container and
userEvent.click to use the returned utilities from the shared render helper so
both tests reuse the same scaffolding.
βΉοΈ Review info
βοΈ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 1a78c230-5eb8-40ed-9851-78cb3030d87e
π Files selected for processing (2)
packages/react-query/src/internals/getClientArgs.tspackages/react-query/test/regression/issue-6862-infinite-query-cursor-initial-load.test.tsx
@trpc/client
@trpc/next
@trpc/openapi
@trpc/react-query
@trpc/server
@trpc/tanstack-react-query
@trpc/upgrade
commit: |
There was a problem hiding this comment.
π§Ή Nitpick comments (1)
packages/react-query/test/queryOptions.test.tsx (1)
52-52: Schema acceptsnullbut handler implicitly relies on JS coercion.
z.number().nullish().default(0)infersnumber | nullas the output type because.default()only fillsundefined, notnull. Whencursor: nullis sent (which this PR now does),input.cursorisnullinside the handler, and the arithmetic/sliceoperations only work due to JS coercion (null + 1 === 1,slice(null, 1) === slice(0, 1)). It also widensinput.cursor's static type tonumber | null.Since the runtime assertions rely on
nullflowing through to React Query'spageParams(not to the server input), normalizing the server input is safe and makes the handler more explicit. Consider transforming inside the schema:β»οΈ Suggested refactor
- cursor: z.number().nullish().default(0), + cursor: z + .number() + .nullish() + .transform((v) => v ?? 0),π€ Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/react-query/test/queryOptions.test.tsx` at line 52, The schema allows null for cursor (z.number().nullish().default(0)) which leaves input.cursor as null at runtime and relies on JS coercion in the handler; update the schema or input transform so cursor is normalized to a number (e.g., map null to 0) before it reaches the handler used by React Query pageParams, ensuring input.cursor has type number and arithmetic/slice logic in the handler (the code referencing cursor/pageParams) no longer depends on coercion.
π€ Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@packages/react-query/test/queryOptions.test.tsx`:
- Line 52: The schema allows null for cursor (z.number().nullish().default(0))
which leaves input.cursor as null at runtime and relies on JS coercion in the
handler; update the schema or input transform so cursor is normalized to a
number (e.g., map null to 0) before it reaches the handler used by React Query
pageParams, ensuring input.cursor has type number and arithmetic/slice logic in
the handler (the code referencing cursor/pageParams) no longer depends on
coercion.
βΉοΈ Review info
βοΈ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 193c4c2d-6305-4f29-a419-0a674fe660f5
π Files selected for processing (6)
packages/react-query/test/queryOptions.test.tsxpackages/react-query/test/regression/issue-2942-useInfiniteQuery-setData.test.tsxpackages/react-query/test/regression/issue-4360-useInfiniteQuery-placeHolderData.test.tsxpackages/react-query/test/useQuery.test.tsxpackages/react-query/test/useSuspenseInfiniteQuery.test.tsxpackages/react-query/test/useUtils.test.tsx
β Files skipped from review due to trivial changes (4)
- packages/react-query/test/useUtils.test.tsx
- packages/react-query/test/regression/issue-2942-useInfiniteQuery-setData.test.tsx
- packages/react-query/test/useQuery.test.tsx
- packages/react-query/test/useSuspenseInfiniteQuery.test.tsx
153a06b to
b279f5e
Compare
There was a problem hiding this comment.
π§Ή Nitpick comments (1)
packages/react-query/src/internals/getClientArgs.ts (1)
25-32: Consider simplifying to match the PR description and avoid edge cases.The implementation diverges slightly from the simpler fix described in the PR (
cursor: infiniteParams.pageParam ?? null):
- Behavior change vs prior code: The old form allowed a truthy
pageParamto overrideinput.cursor. The new form always preservesinput.cursorwhen present and ignorespageParam. For the typicaluseInfiniteQueryflow this is harmless (cursor is not user-supplied in input), but it is a silent semantic change.'cursor' in currentInputbypasses the fix whencursorisundefined: If a caller passes{ cursor: undefined, ... }as input,'cursor' in currentInputreturnstrue, so thenullfallback is skipped and the original 400-error scenario can recur.inon non-object input:currentInput = input ?? {}lets primitives through (e.g., a string/number passed as input). Applying'cursor' in <primitive>throwsTypeError. Unlikely in practice for infinite-query schemas, but worth being defensive.Unless preserving a user-supplied
cursoris intentional (and tested), the simpler form from the PR description is more robust:β»οΈ Suggested simplification
if (infiniteParams) { - const currentInput = input ?? {}; input = { - ...currentInput, - // Only inject cursor if not already in input, defaulting to null when pageParam is undefined - ...(('cursor' in currentInput) ? {} : { cursor: infiniteParams.pageParam ?? null }), + ...(input ?? {}), + cursor: infiniteParams.pageParam ?? null, direction: infiniteParams.direction, }; }If the βpreserve existing cursor in inputβ behavior is deliberate, please add a regression test covering both
{ cursor: undefined }and{ cursor: 'someValue' }ininputso the contract is locked in.π€ Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/react-query/src/internals/getClientArgs.ts` around lines 25 - 32, The current merge logic inside getClientArgs uses "'cursor' in currentInput" which both preserves a user-supplied cursor (changing prior semantics), fails to set the null fallback when input.cursor === undefined, and can throw TypeError for primitive inputs; replace that block so you always inject cursor from infiniteParams: set input = { ...currentInput, cursor: infiniteParams.pageParam ?? null, direction: infiniteParams.direction } (i.e., remove the "'cursor' in currentInput" branch), and if preserving the old "keep user cursor" behavior was intentional, add regression tests around inputs { cursor: undefined } and { cursor: 'someValue' } to lock the contract.
π€ Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@packages/react-query/src/internals/getClientArgs.ts`:
- Around line 25-32: The current merge logic inside getClientArgs uses "'cursor'
in currentInput" which both preserves a user-supplied cursor (changing prior
semantics), fails to set the null fallback when input.cursor === undefined, and
can throw TypeError for primitive inputs; replace that block so you always
inject cursor from infiniteParams: set input = { ...currentInput, cursor:
infiniteParams.pageParam ?? null, direction: infiniteParams.direction } (i.e.,
remove the "'cursor' in currentInput" branch), and if preserving the old "keep
user cursor" behavior was intentional, add regression tests around inputs {
cursor: undefined } and { cursor: 'someValue' } to lock the contract.
βΉοΈ Review info
βοΈ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 1b17831d-f9e8-4d14-bdae-44ab6cd054c6
π Files selected for processing (1)
packages/react-query/src/internals/getClientArgs.ts
a1a9416 to
9b9c724
Compare
|
@coderabbitai review |
|
Only users with a collaborator, contributor, member, or owner role can interact with CodeRabbit. |
β¦inite queries
The truthy check (`pageParam ? { cursor } : {}`) silently dropped falsy
cursors β null and 0 β causing two distinct bugs:
1. pageParam = 0 was omitted, producing wrong data for zero-based cursors.
2. pageParam = null (from an explicit `initialCursor: null` with a
`z.number().nullable()` schema) was omitted, causing a Zod "Required"
validation error on initial load (issue trpc#6862).
Switch to `!== undefined` so null and 0 are forwarded correctly while
undefined β meaning "no cursor, let the schema default apply" β is still
omitted.
`createUtilityFunctions.ts` had three call sites (infiniteQueryOptions,
fetchInfiniteQuery, prefetchInfiniteQuery) that passed the raw TanStack
pageParam (null on initial load) directly to getClientArgs, bypassing the
`pageParam ?? opts.initialCursor` normalization already present in
createHooksInternal.tsx. All three now apply the same conversion so that
null collapses to undefined when no initialCursor is set, ensuring
consistent behaviour across all four infinite-query APIs.
Regression test added for schemas with `z.number().nullable()` cursor;
callers must pass `initialCursor: null` so tRPC forwards null rather than
omitting the field.
Co-authored-by: Alex / KATT <[email protected]>
β¦nfinite and infiniteQueryOptions Co-authored-by: Alex / KATT <[email protected]>
|
π€ Pushed a couple of small maintainer follow-ups on top of your commit (unchanged):
I also edited the description: |
trpc-bot
left a comment
There was a problem hiding this comment.
π€ Verified that this is a real bug: @trpc/react-query dropped falsy cursors (0, null, '') because of a truthy check. #6602 already fixed the same thing in @trpc/tanstack-react-query, and this PR brings @trpc/react-query into line with it.
I merged current main into this branch locally and ran the two issue-6862 test files:
- With
main'sgetClientArgs.tsandcreateUtilityFunctions.ts, 8 of 11 tests fail (ZodRequiredoncursor, and inputs of{}instead of{ cursor: 0 }or{ cursor: null }). - With this PR's code, all 11 pass. The full
react-query,tanstack-react-queryandnextsuites also pass (306 tests), andtscandeslintare clean.
Query keys don't change, because cursor and direction are still stripped from the key. Leaving out initialCursor still sends no cursor.
I couldn't push the main merge to the fork. GitHub rejected it because the bot token lacks workflows permission for .github/workflows/check-skills.yml. Since main requires branches to be up to date, a maintainer needs to click Update branch before this can merge.
|
@KATT is attempting to deploy a commit to the trpc Team on Vercel. A member of the Team first needs to authorize it. |
|
This pull request has been locked because we are very unlikely to see comments on closed issues. If you think, this PR is still necessary, create a new one with the same branch. Thank you. |
Refs #6862
π― Changes
useInfiniteQueryfails on initial render when the cursor schema isz.number().nullable(). The cursor field gets omitted from the request, producing a Zod"Required"validation error before any data loads. A separate issue causes page0cursors to be silently dropped.Root cause
getClientArgs.tsused a truthy check to decide whether to inject cursor:Three call sites in
createUtilityFunctions.ts(infiniteQueryOptions,fetchInfiniteQuery,prefetchInfiniteQuery) also passed TanStack's rawpageParamdirectly togetClientArgs. BecauseinitialPageParamdefaults tonullin tRPC, those paths always receivedpageParam = nullon the first fetch and forwarded it straight through.createHooksInternal.tsxalready appliedpageParam ?? opts.initialCursorto convert that internal null toundefined(meaning "no cursor, apply schema default"), butcreateUtilityFunctions.tswas missing it for all three.Fix
Replace the truthy check with
!== undefined:Apply
pageParam ?? opts?.initialCursorat all three call sites increateUtilityFunctions.tsto matchcreateHooksInternal.tsx.For
z.number().nullable()schemas: passinitialCursor: nullso tRPC forwards null rather than collapsing it to undefined:initialCursor: 0andinitialCursor: nullare now sent to the procedure ascursor: 0/cursor: nullinstead of being dropped. The same applies to agetNextPageParamthat returns0. OmittinginitialCursorstill sends no cursor, as before. This applies touseInfiniteQueryas well asutils.*.fetchInfinite,prefetchInfiniteandinfiniteQueryOptions.β Checklist