From 3ef788786c2275cda14f6c0b0cd2216f4164d82c Mon Sep 17 00:00:00 2001 From: Dominik Dorfmeister Date: Fri, 26 Jul 2024 10:44:32 +0200 Subject: [PATCH] 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 --- packages/query-core/src/__tests__/queryClient.test.tsx | 10 ++++++++-- packages/query-core/src/infiniteQueryBehavior.ts | 3 +++ 2 files changed, 11 insertions(+), 2 deletions(-) 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) } }