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

infiniteQueryBehavior.ts

207 lines6.6 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] === undefined
109 ? options.initialPageParam
110 : oldPageParams[0]
111 : getNextPageParam(options, result)
112 if (currentPage > 0 && param == null) {
113 break
114 }
115 result = await fetchPage(result, param)
116 currentPage++
117 } while (currentPage < remainingPages)
118 }
119​
120 return result
121 }
122 if (context.options.persister) {
123 context.fetchFn = () => {
124 return context.options.persister?.(
125 fetchFn as any,
126 {
127 client: context.client,
128 queryKey: context.queryKey,
129 meta: context.options.meta,
130 signal: context.signal,
131 },
132 query,
133 )
134 }
135 } else {
136 context.fetchFn = fetchFn
137 }
138 },
139 }
141​
142/**
143 * Computes the page param of the page after the last one, with the `getNextPageParam` option.
144 * @param options - The infinite query options.
145 * @param data - The current pages and page params.
146 * @returns The next page param, or `undefined` if there are no pages yet.
147 */
148function getNextPageParam(
149 options: InfiniteQueryPageParamsOptions<any>,
150 { pages, pageParams }: InfiniteData<unknown>,
151): unknown | undefined {
152 const lastIndex = pages.length - 1
153 return pages.length > 0
154 ? options.getNextPageParam(
155 pages[lastIndex],
156 pages,
157 pageParams[lastIndex],
158 pageParams,
159 )
160 : undefined
162​
163/**
164 * Computes the page param of the page before the first one, with the `getPreviousPageParam`
165 * option.
166 * @param options - The infinite query options.
167 * @param data - The current pages and page params.
168 * @returns The previous page param, or `undefined` if there are no pages yet or no
169 * `getPreviousPageParam` option.
170 */
171function getPreviousPageParam(
172 options: InfiniteQueryPageParamsOptions<any>,
173 { pages, pageParams }: InfiniteData<unknown>,
174): unknown | undefined {
175 return pages.length > 0
176 ? options.getPreviousPageParam?.(pages[0], pages, pageParams[0], pageParams)
177 : undefined
179​
180/**
181 * Checks if there is a next page.
182 * @param options - The infinite query options with `getNextPageParam`.
183 * @param data - The current pages and page params.
184 * @returns `true` if `getNextPageParam` returns a value other than `null` or `undefined`.
185 */
186export function hasNextPage(
187 options: InfiniteQueryPageParamsOptions<any, any>,
188 data?: InfiniteData<unknown>,
189): boolean {
190 if (!data) return false
191 return getNextPageParam(options, data) != null
193​
194/**
195 * Checks if there is a previous page.
196 * @param options - The infinite query options with `getPreviousPageParam`.
197 * @param data - The current pages and page params.
198 * @returns `true` if `getPreviousPageParam` is set and returns a value other than `null` or
199 * `undefined`.
200 */
201export function hasPreviousPage(
202 options: InfiniteQueryPageParamsOptions<any, any>,
203 data?: InfiniteData<unknown>,
204): boolean {
205 if (!data || !options.getPreviousPageParam) return false
206 return getPreviousPageParam(options, data) != null