Open History to see the last commit
1import {
2 addConsumeAwareSignal,
3 addToEnd,
4 addToStart,
5 ensureQueryFn,
6} from './utils'
7import type {
8 FetchPageDirectionMode,
9 InfiniteData,
10 InfiniteQueryPageParamsOptions,
11 OmitKeyof,
12 QueryFunctionContext,
13 QueryKey,
14} from './types'
15import type { QueryBehavior } from './query'
16β
17/**
18 * Creates the behavior that fetches the pages of an infinite query: the next or previous page for
19 * `fetchNextPage`/`fetchPreviousPage`, or all pages again from the start on a refetch.
20 * @param pages - The number of pages to fetch from the start when all pages are fetched again,
21 * e.g. from the `pages` option of `queryClient.infiniteQuery`. Defaults to the number of cached
22 * pages.
23 * @returns The query behavior to set on an infinite query.
24 */
25export function infiniteQueryBehavior<
26 TQueryFnData,
27 TError,
28 TData,
29 TPageParam,
30 TMode extends FetchPageDirectionMode = FetchPageDirectionMode,
31>(
32 pages?: number,
33): QueryBehavior<TQueryFnData, TError, InfiniteData<TData, TPageParam>> {
34 return {
35 onFetch: (context, query) => {
36 const options = context.options as InfiniteQueryPageParamsOptions<
37 TQueryFnData,
38 TPageParam,
39 TMode
40 >
41 const fetchMore = context.fetchOptions?.meta?.fetchMore
42 const manual = options.mode === 'manual'
43 const oldPages = context.state.data?.pages || []
44 const oldPageParams = context.state.data?.pageParams || []
45 let result: InfiniteData<unknown> = { pages: [], pageParams: [] }
46 let currentPage = 0
47β
48 const fetchFn = async () => {
49 let cancelled = false
50 const addSignalProperty = (object: unknown) => {
51 addConsumeAwareSignal(
52 object,
53 () => context.signal,
54 () => (cancelled = true),
55 )
56 }
57β
58 const queryFn = ensureQueryFn(context.options, context.fetchOptions)
59β
60 // Create function to fetch a page
61 const fetchPage = async (
62 data: InfiniteData<unknown>,
63 param: unknown,
64 previous?: boolean,
65 ): Promise<InfiniteData<unknown>> => {
66 if (cancelled) {
67 return Promise.reject(context.signal.reason)
68 }
69β
70 if (!manual && param == null && data.pages.length) {
71 return Promise.resolve(data)
72 }
73β
74 const createQueryFnContext = () => {
75 const queryFnContext: OmitKeyof<
76 QueryFunctionContext<QueryKey, unknown>,
77 'signal'
78 > = {
79 client: context.client,
80 queryKey: context.queryKey,
81 pageParam: param,
82 direction: previous ? 'backward' : 'forward',
83 meta: context.options.meta,
84 }
85 addSignalProperty(queryFnContext)
86 return queryFnContext as QueryFunctionContext<QueryKey, unknown>
87 }
88β
89 const queryFnContext = createQueryFnContext()
90β
91 const page = await queryFn(queryFnContext)
92β
93 const { maxPages } = context.options
94 const addTo = previous ? addToStart : addToEnd
95β
96 return {
97 pages: addTo(data.pages, page, maxPages),
98 pageParams: addTo(data.pageParams, param, maxPages),
99 }
100 }
101β
102 // fetch next / previous page?
103 if (fetchMore && (oldPages.length || manual)) {
104 const previous = fetchMore.direction === 'backward'
105 const pageParamFn = previous ? getPreviousPageParam : getNextPageParam
106 const oldData = {
107 pages: oldPages,
108 pageParams: oldPageParams,
109 }
110 const param = manual
111 ? fetchMore.pageParam
112 : pageParamFn(options, oldData)
113β
114 result = await fetchPage(oldData, param, previous)
115 } else {
116 const remainingPages = manual
117 ? oldPages.length
118 : (pages ?? oldPages.length)
119β
120 // Fetch all pages
121 do {
122 const param = manual
123 ? currentPage < oldPageParams.length
124 ? oldPageParams[currentPage]
125 : options.initialPageParam
126 : currentPage === 0
127 ? (oldPageParams[0] ?? options.initialPageParam)
128 : getNextPageParam(options, result)
129 if (!manual && currentPage > 0 && param == null) {
130 break
131 }
132 result = await fetchPage(result, param)
133 currentPage++
134 } while (currentPage < remainingPages)
135 }
136β
137 return result
138 }
139 if (context.options.persister) {
140 context.fetchFn = () => {
141 return context.options.persister?.(
142 fetchFn as any,
143 {
144 client: context.client,
145 queryKey: context.queryKey,
146 meta: context.options.meta,
147 signal: context.signal,
148 },
149 query,
150 )
151 }
152 } else {
153 context.fetchFn = fetchFn
154 }
155 },
156 }
157}
158β
159/**
160 * Computes the page param of the page after the last one, with the `getNextPageParam` option.
161 * @param options - The infinite query options.
162 * @param data - The current pages and page params.
163 * @returns The next page param, or `undefined` if there are no pages yet.
164 */
165function getNextPageParam(
166 options: InfiniteQueryPageParamsOptions<any, any, any>,
167 { pages, pageParams }: InfiniteData<unknown>,
168): unknown | undefined {
169 const lastIndex = pages.length - 1
170 return pages.length > 0
171 ? options.getNextPageParam?.(
172 pages[lastIndex],
173 pages,
174 pageParams[lastIndex],
175 pageParams,
176 )
177 : undefined
178}
179β
180/**
181 * Computes the page param of the page before the first one, with the `getPreviousPageParam`
182 * option.
183 * @param options - The infinite query options.
184 * @param data - The current pages and page params.
185 * @returns The previous page param, or `undefined` if there are no pages yet or no
186 * `getPreviousPageParam` option.
187 */
188function getPreviousPageParam(
189 options: InfiniteQueryPageParamsOptions<any, any, any>,
190 { pages, pageParams }: InfiniteData<unknown>,
191): unknown | undefined {
192 return pages.length > 0
193 ? options.getPreviousPageParam?.(pages[0], pages, pageParams[0], pageParams)
194 : undefined
195}
196β
197/**
198 * Checks if there is a next page.
199 * @param options - The infinite query options with `getNextPageParam`.
200 * @param data - The current pages and page params.
201 * @returns `true` if `getNextPageParam` returns a value other than `null` or `undefined`.
202 */
203export function hasNextPage(
204 options: InfiniteQueryPageParamsOptions<any, any, any>,
205 data?: InfiniteData<unknown>,
206): boolean {
207 if (!data || options.mode === 'manual') return false
208 return getNextPageParam(options, data) != null
209}
210β
211/**
212 * Checks if there is a previous page.
213 * @param options - The infinite query options with `getPreviousPageParam`.
214 * @param data - The current pages and page params.
215 * @returns `true` if `getPreviousPageParam` is set and returns a value other than `null` or
216 * `undefined`.
217 */
218export function hasPreviousPage(
219 options: InfiniteQueryPageParamsOptions<any, any, any>,
220 data?: InfiniteData<unknown>,
221): boolean {
222 if (!data || options.mode === 'manual') {
223 return false
224 }
225 return getPreviousPageParam(options, data) != null
226}