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