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

infiniteQueryBehavior.ts

176 lines5.0 KB

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