Open History to see the last commit
1import { addToEnd, addToStart, skipToken } from './utils'
2import type { QueryBehavior } from './query'
3import type {
4 InfiniteData,
5 InfiniteQueryPageParamsOptions,
6 OmitKeyof,
7 QueryFunctionContext,
8 QueryKey,
9} from './types'
10β
11export function infiniteQueryBehavior<TQueryFnData, TError, TData, TPageParam>(
12 pages?: number,
13): QueryBehavior<TQueryFnData, TError, InfiniteData<TData, TPageParam>> {
14 return {
15 onFetch: (context, query) => {
16 const fetchFn = async () => {
17 const options = context.options as InfiniteQueryPageParamsOptions<TData>
18 const direction = context.fetchOptions?.meta?.fetchMore?.direction
19 const oldPages = context.state.data?.pages || []
20 const oldPageParams = context.state.data?.pageParams || []
21 const empty = { pages: [], pageParams: [] }
22 let cancelled = false
23β
24 const addSignalProperty = (object: unknown) => {
25 Object.defineProperty(object, 'signal', {
26 enumerable: true,
27 get: () => {
28 if (context.signal.aborted) {
29 cancelled = true
30 } else {
31 context.signal.addEventListener('abort', () => {
32 cancelled = true
33 })
34 }
35 return context.signal
36 },
37 })
38 }
39β
40 // Get query function
41 const queryFn =
42 context.options.queryFn && context.options.queryFn !== skipToken
43 ? context.options.queryFn
44 : () => {
45 if (process.env.NODE_ENV !== 'production') {
46 if (context.options.queryFn === skipToken) {
47 console.error(
48 `Attempted to invoke queryFn when set to skipToken. This is likely a configuration error. Query hash: '${context.options.queryHash}'`,
49 )
50 }
51 }
52 return Promise.reject(
53 new Error(`Missing queryFn: '${context.options.queryHash}'`),
54 )
55 }
56β
57 // Create function to fetch a page
58 const fetchPage = async (
59 data: InfiniteData<unknown>,
60 param: unknown,
61 previous?: boolean,
62 ): Promise<InfiniteData<unknown>> => {
63 if (cancelled) {
64 return Promise.reject()
65 }
66β
67 if (param == null && data.pages.length) {
68 return Promise.resolve(data)
69 }
70β
71 const queryFnContext: OmitKeyof<
72 QueryFunctionContext<QueryKey, unknown>,
73 'signal'
74 > = {
75 queryKey: context.queryKey,
76 pageParam: param,
77 direction: previous ? 'backward' : 'forward',
78 meta: context.options.meta,
79 }
80β
81 addSignalProperty(queryFnContext)
82β
83 const page = await queryFn(
84 queryFnContext as QueryFunctionContext<QueryKey, unknown>,
85 )
86β
87 const { maxPages } = context.options
88 const addTo = previous ? addToStart : addToEnd
89β
90 return {
91 pages: addTo(data.pages, page, maxPages),
92 pageParams: addTo(data.pageParams, param, maxPages),
93 }
94 }
95β
96 let result: InfiniteData<unknown>
97β
98 // fetch next / previous page?
99 if (direction && oldPages.length) {
100 const previous = direction === 'backward'
101 const pageParamFn = previous ? getPreviousPageParam : getNextPageParam
102 const oldData = {
103 pages: oldPages,
104 pageParams: oldPageParams,
105 }
106 const param = pageParamFn(options, oldData)
107β
108 result = await fetchPage(oldData, param, previous)
109 } else {
110 // Fetch first page
111 result = await fetchPage(
112 empty,
113 oldPageParams[0] ?? options.initialPageParam,
114 )
115β
116 const remainingPages = pages ?? oldPages.length
117β
118 // Fetch remaining pages
119 for (let i = 1; i < remainingPages; i++) {
120 const param = getNextPageParam(options, result)
121 result = await fetchPage(result, param)
122 }
123 }
124β
125 return result
126 }
127 if (context.options.persister) {
128 context.fetchFn = () => {
129 return context.options.persister?.(
130 fetchFn as any,
131 {
132 queryKey: context.queryKey,
133 meta: context.options.meta,
134 signal: context.signal,
135 },
136 query,
137 )
138 }
139 } else {
140 context.fetchFn = fetchFn
141 }
142 },
143 }
144}
145β
146function getNextPageParam(
147 options: InfiniteQueryPageParamsOptions<any>,
148 { pages, pageParams }: InfiniteData<unknown>,
149): unknown | undefined {
150 const lastIndex = pages.length - 1
151 return options.getNextPageParam(
152 pages[lastIndex],
153 pages,
154 pageParams[lastIndex],
155 pageParams,
156 )
157}
158β
159function getPreviousPageParam(
160 options: InfiniteQueryPageParamsOptions<any>,
161 { pages, pageParams }: InfiniteData<unknown>,
162): unknown | undefined {
163 return options.getPreviousPageParam?.(
164 pages[0],
165 pages,
166 pageParams[0],
167 pageParams,
168 )
169}
170β
171/**
172 * Checks if there is a next page.
173 */
174export function hasNextPage(
175 options: InfiniteQueryPageParamsOptions<any, any>,
176 data?: InfiniteData<unknown>,
177): boolean {
178 if (!data) return false
179 return getNextPageParam(options, data) != null
180}
181β
182/**
183 * Checks if there is a previous page.
184 */
185export function hasPreviousPage(
186 options: InfiniteQueryPageParamsOptions<any, any>,
187 data?: InfiniteData<unknown>,
188): boolean {
189 if (!data || !options.getPreviousPageParam) return false
190 return getPreviousPageParam(options, data) != null
191}