Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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