Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(core): do not invoke getNextPageParam or getPreviousPageParam if there is we have empty pages in the cache #7743

Merged
merged 2 commits into from
Jul 17, 2024
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
Loading