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

infiniteQueryBehavior.ts

220 lines6.3 KB

1import type { QueryBehavior } from './query'
2​
3import type {
4 InfiniteData,
5 QueryFunctionContext,
6 QueryOptions,
7 RefetchQueryFilters,
8} from './types'
9​
10export function infiniteQueryBehavior<
11 TQueryFnData,
12 TError,
13 TData,
14>(): QueryBehavior<TQueryFnData, TError, InfiniteData<TData>> {
15 return {
16 onFetch: (context) => {
17 context.fetchFn = () => {
18 const refetchPage: RefetchQueryFilters['refetchPage'] | undefined =
19 context.fetchOptions?.meta?.refetchPage
20 const fetchMore = context.fetchOptions?.meta?.fetchMore
21 const pageParam = fetchMore?.pageParam
22 const isFetchingNextPage = fetchMore?.direction === 'forward'
23 const isFetchingPreviousPage = fetchMore?.direction === 'backward'
24 const oldPages = context.state.data?.pages || []
25 const oldPageParams = context.state.data?.pageParams || []
26 let newPageParams = oldPageParams
27 let cancelled = false
28​
29 const addSignalProperty = (object: unknown) => {
30 Object.defineProperty(object, 'signal', {
31 enumerable: true,
32 get: () => {
33 if (context.signal?.aborted) {
34 cancelled = true
35 } else {
36 context.signal?.addEventListener('abort', () => {
37 cancelled = true
38 })
39 }
40 return context.signal
41 },
42 })
43 }
44​
45 // Get query function
46 const queryFn =
47 context.options.queryFn ||
48 (() =>
49 Promise.reject(
50 `Missing queryFn for queryKey '${context.options.queryHash}'`,
51 ))
52​
53 const buildNewPages = (
54 pages: unknown[],
55 param: unknown,
56 page: unknown,
57 previous?: boolean,
58 ) => {
59 newPageParams = previous
60 ? [param, ...newPageParams]
61 : [...newPageParams, param]
62 return previous ? [page, ...pages] : [...pages, page]
63 }
64​
65 // Create function to fetch a page
66 const fetchPage = (
67 pages: unknown[],
68 manual?: boolean,
69 param?: unknown,
70 previous?: boolean,
71 ): Promise<unknown[]> => {
72 if (cancelled) {
73 return Promise.reject('Cancelled')
74 }
75​
76 if (typeof param === 'undefined' && !manual && pages.length) {
77 return Promise.resolve(pages)
78 }
79​
80 const queryFnContext: QueryFunctionContext = {
81 queryKey: context.queryKey,
82 pageParam: param,
83 meta: context.options.meta,
84 }
85​
86 addSignalProperty(queryFnContext)
87​
88 const queryFnResult = queryFn(queryFnContext)
89​
90 const promise = Promise.resolve(queryFnResult).then((page) =>
91 buildNewPages(pages, param, page, previous),
92 )
93​
94 return promise
95 }
96​
97 let promise: Promise<unknown[]>
98​
99 // Fetch first page?
100 if (!oldPages.length) {
101 promise = fetchPage([])
102 }
103​
104 // Fetch next page?
105 else if (isFetchingNextPage) {
106 const manual = typeof pageParam !== 'undefined'
107 const param = manual
108 ? pageParam
109 : getNextPageParam(context.options, oldPages)
110 promise = fetchPage(oldPages, manual, param)
111 }
112​
113 // Fetch previous page?
114 else if (isFetchingPreviousPage) {
115 const manual = typeof pageParam !== 'undefined'
116 const param = manual
117 ? pageParam
118 : getPreviousPageParam(context.options, oldPages)
119 promise = fetchPage(oldPages, manual, param, true)
120 }
121​
122 // Refetch pages
123 else {
124 newPageParams = []
125​
126 const manual = typeof context.options.getNextPageParam === 'undefined'
127​
128 const shouldFetchFirstPage =
129 refetchPage && oldPages[0]
130 ? refetchPage(oldPages[0], 0, oldPages)
131 : true
132​
133 // Fetch first page
134 promise = shouldFetchFirstPage
135 ? fetchPage([], manual, oldPageParams[0])
136 : Promise.resolve(buildNewPages([], oldPageParams[0], oldPages[0]))
137​
138 // Fetch remaining pages
139 for (let i = 1; i < oldPages.length; i++) {
140 promise = promise.then((pages) => {
141 const shouldFetchNextPage =
142 refetchPage && oldPages[i]
143 ? refetchPage(oldPages[i], i, oldPages)
144 : true
145​
146 if (shouldFetchNextPage) {
147 const param = manual
148 ? oldPageParams[i]
149 : getNextPageParam(context.options, pages)
150 return fetchPage(pages, manual, param)
151 }
152 return Promise.resolve(
153 buildNewPages(pages, oldPageParams[i], oldPages[i]),
154 )
155 })
156 }
157 }
158​
159 const finalPromise = promise.then((pages) => ({
160 pages,
161 pageParams: newPageParams,
162 }))
163​
164 return finalPromise
165 }
166 },
167 }
169​
170export function getNextPageParam(
171 options: QueryOptions<any, any>,
172 pages: unknown[],
173): unknown | undefined {
174 return options.getNextPageParam?.(pages[pages.length - 1], pages)
176​
177export function getPreviousPageParam(
178 options: QueryOptions<any, any>,
179 pages: unknown[],
180): unknown | undefined {
181 return options.getPreviousPageParam?.(pages[0], pages)
183​
184/**
185 * Checks if there is a next page.
186 * Returns `undefined` if it cannot be determined.
187 */
188export function hasNextPage(
189 options: QueryOptions<any, any, any, any>,
190 pages?: unknown,
191): boolean | undefined {
192 if (options.getNextPageParam && Array.isArray(pages)) {
193 const nextPageParam = getNextPageParam(options, pages)
194 return (
195 typeof nextPageParam !== 'undefined' &&
196 nextPageParam !== null &&
197 nextPageParam !== false
198 )
199 }
200 return
202​
203/**
204 * Checks if there is a previous page.
205 * Returns `undefined` if it cannot be determined.
206 */
207export function hasPreviousPage(
208 options: QueryOptions<any, any, any, any>,
209 pages?: unknown,
210): boolean | undefined {
211 if (options.getPreviousPageParam && Array.isArray(pages)) {
212 const previousPageParam = getPreviousPageParam(options, pages)
213 return (
214 typeof previousPageParam !== 'undefined' &&
215 previousPageParam !== null &&
216 previousPageParam !== false
217 )
218 }
219 return