fix(query-core): guard against undefined pages in hasNextPage/hasPreviousPage#11001
fix(query-core): guard against undefined pages in hasNextPage/hasPreviousPage#11001ZacharyL2 wants to merge 1 commit into
Conversation
…iousPage A malformed InfiniteData whose `pages` is undefined (e.g. from SSR hydration or setQueryData) reached getNextPageParam and threw "Cannot read properties of undefined (reading 'length')". Treat the data as Partial and guard before indexing, matching the existing state.data?.pages handling in onFetch.
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (3)
📝 WalkthroughWalkthroughGuards ChangesInfinite Query pages undefined guard
Estimated code review effort🎯 2 (Simple) | ⏱️ ~5 minutes Poem
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
Summary
hasNextPage/hasPreviousPagecrash withTypeError: Cannot read properties of undefined (reading 'length')whenstate.datais a malformedInfiniteDatawhosepagesisundefined.The
InfiniteDatainterface declarespages: Array<TData>as required, which is true for data produced byinfiniteQueryBehavior's own fetch. Butstate.datacan also be populated from outside that path — SSR hydration, a manualsetQueryData, or a persisted/restored cache — where the object may not honor the type. When such data reachesgetNextPageParam, the unconditionalpages.lengththrows.Notably,
onFetchin the same file already anticipates this:getNextPageParam/getPreviousPageParam/hasNextPage/hasPreviousPagesimply didn't get the same defensive treatment. This PR makes them consistent.Crash
Seen in production on a TanStack Start (SSR) app across multiple infinite queries; intermittent, tied to hydration timing.
Change
dataargument ofgetNextPageParam/getPreviousPageParamasPartial<InfiniteData<unknown>>to reflect that it can be malformed at runtime (noascasts).if (!pages?.length) return undefinedbefore indexing.pagesis a valid non-empty array the behavior is unchanged —pageParams ?? []is a no-op on well-formed data, sincepagesandpageParamsare always written together.The result: a malformed
pagesnow yields "no next/previous page" instead of throwing, sohasNextPage/hasPreviousPagereturnfalse.Test
Added a regression test asserting
hasNextPage/hasPreviousPagereturnfalse(instead of throwing) for malformedInfiniteData. It fails without this change.Changeset
Included as a
patchfor@tanstack/query-core.Summary by CodeRabbit