Skip to content

Commit 7edf587

Browse files
authoredJul 17, 2024··
fix(core): do not invoke getNextPageParam or getPreviousPageParam if there is we have empty pages in the cache (#7743)
1 parent a1ce3c4 commit 7edf587

File tree

2 files changed

+46
-12
lines changed

2 files changed

+46
-12
lines changed
 

‎packages/query-core/src/__tests__/infiniteQueryObserver.test.tsx

+35
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,41 @@ describe('InfiniteQueryObserver', () => {
103103
expect(all).toEqual(['next0', 'next0,1', 'prev0,1'])
104104
})
105105

106+
test('should not invoke getNextPageParam and getPreviousPageParam on empty pages', async () => {
107+
const key = queryKey()
108+
109+
const getNextPageParam = vi.fn()
110+
const getPreviousPageParam = vi.fn()
111+
112+
const observer = new InfiniteQueryObserver(queryClient, {
113+
queryKey: key,
114+
queryFn: ({ pageParam }) => String(pageParam),
115+
initialPageParam: 1,
116+
getNextPageParam: getNextPageParam.mockImplementation(
117+
(_, __, lastPageParam) => {
118+
return lastPageParam + 1
119+
},
120+
),
121+
getPreviousPageParam: getPreviousPageParam.mockImplementation(
122+
(_, __, firstPageParam) => {
123+
return firstPageParam - 1
124+
},
125+
),
126+
})
127+
128+
const unsubscribe = observer.subscribe(() => {})
129+
130+
getNextPageParam.mockClear()
131+
getPreviousPageParam.mockClear()
132+
133+
queryClient.setQueryData(key, { pages: [], pageParams: [] })
134+
135+
expect(getNextPageParam).toHaveBeenCalledTimes(0)
136+
expect(getPreviousPageParam).toHaveBeenCalledTimes(0)
137+
138+
unsubscribe()
139+
})
140+
106141
test('should stop refetching if undefined is returned from getNextPageParam', async () => {
107142
const key = queryKey()
108143
let next: number | undefined = 2

‎packages/query-core/src/infiniteQueryBehavior.ts

+11-12
Original file line numberDiff line numberDiff line change
@@ -133,24 +133,23 @@ function getNextPageParam(
133133
{ pages, pageParams }: InfiniteData<unknown>,
134134
): unknown | undefined {
135135
const lastIndex = pages.length - 1
136-
return options.getNextPageParam(
137-
pages[lastIndex],
138-
pages,
139-
pageParams[lastIndex],
140-
pageParams,
141-
)
136+
return pages.length > 0
137+
? options.getNextPageParam(
138+
pages[lastIndex],
139+
pages,
140+
pageParams[lastIndex],
141+
pageParams,
142+
)
143+
: undefined
142144
}
143145

144146
function getPreviousPageParam(
145147
options: InfiniteQueryPageParamsOptions<any>,
146148
{ pages, pageParams }: InfiniteData<unknown>,
147149
): unknown | undefined {
148-
return options.getPreviousPageParam?.(
149-
pages[0],
150-
pages,
151-
pageParams[0],
152-
pageParams,
153-
)
150+
return pages.length > 0
151+
? options.getPreviousPageParam?.(pages[0], pages, pageParams[0], pageParams)
152+
: undefined
154153
}
155154

156155
/**

0 commit comments

Comments
 (0)
Please sign in to comment.