Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

infiniteQueryBehavior.ts

205 lines6.5 KB

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