Skip to content

Commit

Permalink
fix(core): do not invoke getNextPageParam or getPreviousPageParam if …
Browse files Browse the repository at this point in the history
…there is we have empty pages in the cache (#7743)
  • Loading branch information
TkDodo committed Jul 17, 2024
1 parent a1ce3c4 commit 7edf587
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 12 deletions.
35 changes: 35 additions & 0 deletions packages/query-core/src/__tests__/infiniteQueryObserver.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,41 @@ describe('InfiniteQueryObserver', () => {
expect(all).toEqual(['next0', 'next0,1', 'prev0,1'])
})

test('should not invoke getNextPageParam and getPreviousPageParam on empty pages', async () => {
const key = queryKey()

const getNextPageParam = vi.fn()
const getPreviousPageParam = vi.fn()

const observer = new InfiniteQueryObserver(queryClient, {
queryKey: key,
queryFn: ({ pageParam }) => String(pageParam),
initialPageParam: 1,
getNextPageParam: getNextPageParam.mockImplementation(
(_, __, lastPageParam) => {
return lastPageParam + 1
},
),
getPreviousPageParam: getPreviousPageParam.mockImplementation(
(_, __, firstPageParam) => {
return firstPageParam - 1
},
),
})

const unsubscribe = observer.subscribe(() => {})

getNextPageParam.mockClear()
getPreviousPageParam.mockClear()

queryClient.setQueryData(key, { pages: [], pageParams: [] })

expect(getNextPageParam).toHaveBeenCalledTimes(0)
expect(getPreviousPageParam).toHaveBeenCalledTimes(0)

unsubscribe()
})

test('should stop refetching if undefined is returned from getNextPageParam', async () => {
const key = queryKey()
let next: number | undefined = 2
Expand Down
23 changes: 11 additions & 12 deletions packages/query-core/src/infiniteQueryBehavior.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,24 +133,23 @@ function getNextPageParam(
{ pages, pageParams }: InfiniteData<unknown>,
): unknown | undefined {
const lastIndex = pages.length - 1
return options.getNextPageParam(
pages[lastIndex],
pages,
pageParams[lastIndex],
pageParams,
)
return pages.length > 0
? options.getNextPageParam(
pages[lastIndex],
pages,
pageParams[lastIndex],
pageParams,
)
: undefined
}

function getPreviousPageParam(
options: InfiniteQueryPageParamsOptions<any>,
{ pages, pageParams }: InfiniteData<unknown>,
): unknown | undefined {
return options.getPreviousPageParam?.(
pages[0],
pages,
pageParams[0],
pageParams,
)
return pages.length > 0
? options.getPreviousPageParam?.(pages[0], pages, pageParams[0], pageParams)
: undefined
}

/**
Expand Down

0 comments on commit 7edf587

Please sign in to comment.