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