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

infiniteQueryBehavior.ts

176 lines5.0 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​
16export function infiniteQueryBehavior<TQueryFnData, TError, TData, TPageParam>(
17 pages?: number,
18): QueryBehavior<TQueryFnData, TError, InfiniteData<TData, TPageParam>> {
19 return {
20 onFetch: (context, query) => {
21 const options = context.options as InfiniteQueryPageParamsOptions<TData>
22 const direction = context.fetchOptions?.meta?.fetchMore?.direction
23 const oldPages = context.state.data?.pages || []
24 const oldPageParams = context.state.data?.pageParams || []
25 let result: InfiniteData<unknown> = { pages: [], pageParams: [] }
26 let currentPage = 0
27​
28 const fetchFn = async () => {
29 let cancelled = false
30 const addSignalProperty = (object: unknown) => {
31 addConsumeAwareSignal(
32 object,
33 () => context.signal,
34 () => (cancelled = true),
35 )
36 }
37​
38 const queryFn = ensureQueryFn(context.options, context.fetchOptions)
39​
40 // Create function to fetch a page
41 const fetchPage = async (
42 data: InfiniteData<unknown>,
43 param: unknown,
44 previous?: boolean,
45 ): Promise<InfiniteData<unknown>> => {
46 if (cancelled) {
47 return Promise.reject()
48 }
49​
50 if (param == null && data.pages.length) {
51 return Promise.resolve(data)
52 }
53​
54 const createQueryFnContext = () => {
55 const queryFnContext: OmitKeyof<
56 QueryFunctionContext<QueryKey, unknown>,
57 'signal'
58 > = {
59 client: context.client,
60 queryKey: context.queryKey,
61 pageParam: param,
62 direction: previous ? 'backward' : 'forward',
63 meta: context.options.meta,
64 }
65 addSignalProperty(queryFnContext)
66 return queryFnContext as QueryFunctionContext<QueryKey, unknown>
67 }
68​
69 const queryFnContext = createQueryFnContext()
70​
71 const page = await queryFn(queryFnContext)
72​
73 const { maxPages } = context.options
74 const addTo = previous ? addToStart : addToEnd
75​
76 return {
77 pages: addTo(data.pages, page, maxPages),
78 pageParams: addTo(data.pageParams, param, maxPages),
79 }
80 }
81​
82 // fetch next / previous page?
83 if (direction && oldPages.length) {
84 const previous = direction === 'backward'
85 const pageParamFn = previous ? getPreviousPageParam : getNextPageParam
86 const oldData = {
87 pages: oldPages,
88 pageParams: oldPageParams,
89 }
90 const param = pageParamFn(options, oldData)
91​
92 result = await fetchPage(oldData, param, previous)
93 } else {
94 const remainingPages = pages ?? oldPages.length
95​
96 // Fetch all pages
97 do {
98 const param =
99 currentPage === 0
100 ? (oldPageParams[0] ?? options.initialPageParam)
101 : getNextPageParam(options, result)
102 if (currentPage > 0 && param == null) {
103 break
104 }
105 result = await fetchPage(result, param)
106 currentPage++
107 } while (currentPage < remainingPages)
108 }
109​
110 return result
111 }
112 if (context.options.persister) {
113 context.fetchFn = () => {
114 return context.options.persister?.(
115 fetchFn as any,
116 {
117 client: context.client,
118 queryKey: context.queryKey,
119 meta: context.options.meta,
120 signal: context.signal,
121 },
122 query,
123 )
124 }
125 } else {
126 context.fetchFn = fetchFn
127 }
128 },
129 }
131​
132function getNextPageParam(
133 options: InfiniteQueryPageParamsOptions<any>,
134 { pages, pageParams }: InfiniteData<unknown>,
135): unknown | undefined {
136 const lastIndex = pages.length - 1
137 return pages.length > 0
138 ? options.getNextPageParam(
139 pages[lastIndex],
140 pages,
141 pageParams[lastIndex],
142 pageParams,
143 )
144 : undefined
146​
147function getPreviousPageParam(
148 options: InfiniteQueryPageParamsOptions<any>,
149 { pages, pageParams }: InfiniteData<unknown>,
150): unknown | undefined {
151 return pages.length > 0
152 ? options.getPreviousPageParam?.(pages[0], pages, pageParams[0], pageParams)
153 : undefined
155​
156/**
157 * Checks if there is a next page.
158 */
159export function hasNextPage(
160 options: InfiniteQueryPageParamsOptions<any, any>,
161 data?: InfiniteData<unknown>,
162): boolean {
163 if (!data) return false
164 return getNextPageParam(options, data) != null
166​
167/**
168 * Checks if there is a previous page.
169 */
170export function hasPreviousPage(
171 options: InfiniteQueryPageParamsOptions<any, any>,
172 data?: InfiniteData<unknown>,
173): boolean {
174 if (!data || !options.getPreviousPageParam) return false
175 return getPreviousPageParam(options, data) != null