Skip to content

Commit 3ef7887

Browse files
authored
fix(query-core): abort fetch loop for infinite queries if getNextPageParam returns null or undefined (#7799)
The `fetchPage` function has a safeguard where it only returns the current data if pageParam == null, however, this means we still stay in the loop and call `getNextPageParam` unnecessarily. This can be troublesome if you set `pages: Infinity` on queryClient.fetchInfiniteQuery to fetch an arbitrary amount of pages until the natural end is reached by returning null/undefined from getNextPageParam, because it would never actually escape the loop
1 parent 34a5672 commit 3ef7887

File tree

2 files changed

+11
-2
lines changed

2 files changed

+11
-2
lines changed

packages/query-core/src/__tests__/queryClient.test.tsx

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -746,12 +746,15 @@ describe('queryClient', () => {
746746

747747
test('should stop prefetching if getNextPageParam returns undefined', async () => {
748748
const key = queryKey()
749+
let count = 0
749750

750751
await queryClient.prefetchInfiniteQuery({
751752
queryKey: key,
752753
queryFn: ({ pageParam }) => String(pageParam),
753-
getNextPageParam: (_lastPage, _pages, lastPageParam) =>
754-
lastPageParam >= 20 ? undefined : lastPageParam + 5,
754+
getNextPageParam: (_lastPage, _pages, lastPageParam) => {
755+
count++
756+
return lastPageParam >= 20 ? undefined : lastPageParam + 5
757+
},
755758
initialPageParam: 10,
756759
pages: 5,
757760
})
@@ -762,6 +765,9 @@ describe('queryClient', () => {
762765
pages: ['10', '15', '20'],
763766
pageParams: [10, 15, 20],
764767
})
768+
769+
// this check ensures we're exiting the fetch loop early
770+
expect(count).toBe(3)
765771
})
766772
})
767773

packages/query-core/src/infiniteQueryBehavior.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,9 @@ export function infiniteQueryBehavior<TQueryFnData, TError, TData, TPageParam>(
103103
// Fetch remaining pages
104104
for (let i = 1; i < remainingPages; i++) {
105105
const param = getNextPageParam(options, result)
106+
if (param == null) {
107+
break
108+
}
106109
result = await fetchPage(result, param)
107110
}
108111
}

0 commit comments

Comments
 (0)