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