diff --git a/packages/query-core/src/__tests__/queryClient.test.tsx b/packages/query-core/src/__tests__/queryClient.test.tsx index 6530ec9974..2468f5834d 100644 --- a/packages/query-core/src/__tests__/queryClient.test.tsx +++ b/packages/query-core/src/__tests__/queryClient.test.tsx @@ -746,12 +746,15 @@ describe('queryClient', () => { test('should stop prefetching if getNextPageParam returns undefined', async () => { const key = queryKey() + let count = 0 await queryClient.prefetchInfiniteQuery({ queryKey: key, queryFn: ({ pageParam }) => String(pageParam), - getNextPageParam: (_lastPage, _pages, lastPageParam) => - lastPageParam >= 20 ? undefined : lastPageParam + 5, + getNextPageParam: (_lastPage, _pages, lastPageParam) => { + count++ + return lastPageParam >= 20 ? undefined : lastPageParam + 5 + }, initialPageParam: 10, pages: 5, }) @@ -762,6 +765,9 @@ describe('queryClient', () => { pages: ['10', '15', '20'], pageParams: [10, 15, 20], }) + + // this check ensures we're exiting the fetch loop early + expect(count).toBe(3) }) }) diff --git a/packages/query-core/src/infiniteQueryBehavior.ts b/packages/query-core/src/infiniteQueryBehavior.ts index 90bf8af2a4..5db6e34ba1 100644 --- a/packages/query-core/src/infiniteQueryBehavior.ts +++ b/packages/query-core/src/infiniteQueryBehavior.ts @@ -103,6 +103,9 @@ export function infiniteQueryBehavior( // Fetch remaining pages for (let i = 1; i < remainingPages; i++) { const param = getNextPageParam(options, result) + if (param == null) { + break + } result = await fetchPage(result, param) } }