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