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

infiniteQueryBehavior.ts

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