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

infiniteQueryBehavior.ts

175 lines5.1 KB

1import { addToEnd, addToStart, ensureQueryFn } 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 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 let result: InfiniteData<unknown> = { pages: [], pageParams: [] }
21 let currentPage = 0
22​
23 const fetchFn = async () => {
24 let cancelled = false
25 const addSignalProperty = (object: unknown) => {
26 Object.defineProperty(object, 'signal', {
27 enumerable: true,
28 get: () => {
29 if (context.signal.aborted) {
30 cancelled = true
31 } else {
32 context.signal.addEventListener('abort', () => {
33 cancelled = true
34 })
35 }
36 return context.signal
37 },
38 })
39 }
40​
41 const queryFn = ensureQueryFn(context.options, context.fetchOptions)
42​
43 // Create function to fetch a page
44 const fetchPage = async (
45 data: InfiniteData<unknown>,
46 param: unknown,
47 previous?: boolean,
48 ): Promise<InfiniteData<unknown>> => {
49 if (cancelled) {
50 return Promise.reject()
51 }
52​
53 if (param == null && data.pages.length) {
54 return Promise.resolve(data)
55 }
56​
57 const queryFnContext: OmitKeyof<
58 QueryFunctionContext<QueryKey, unknown>,
59 'signal'
60 > = {
61 queryKey: context.queryKey,
62 pageParam: param,
63 direction: previous ? 'backward' : 'forward',
64 meta: context.options.meta,
65 }
66​
67 addSignalProperty(queryFnContext)
68​
69 const page = await queryFn(
70 queryFnContext as QueryFunctionContext<QueryKey, unknown>,
71 )
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 queryKey: context.queryKey,
118 meta: context.options.meta,
119 signal: context.signal,
120 },
121 query,
122 )
123 }
124 } else {
125 context.fetchFn = fetchFn
126 }
127 },
128 }
130​
131function getNextPageParam(
132 options: InfiniteQueryPageParamsOptions<any>,
133 { pages, pageParams }: InfiniteData<unknown>,
134): unknown | undefined {
135 const lastIndex = pages.length - 1
136 return pages.length > 0
137 ? options.getNextPageParam(
138 pages[lastIndex],
139 pages,
140 pageParams[lastIndex],
141 pageParams,
142 )
143 : undefined
145​
146function getPreviousPageParam(
147 options: InfiniteQueryPageParamsOptions<any>,
148 { pages, pageParams }: InfiniteData<unknown>,
149): unknown | undefined {
150 return pages.length > 0
151 ? options.getPreviousPageParam?.(pages[0], pages, pageParams[0], pageParams)
152 : undefined
154​
155/**
156 * Checks if there is a next page.
157 */
158export function hasNextPage(
159 options: InfiniteQueryPageParamsOptions<any, any>,
160 data?: InfiniteData<unknown>,
161): boolean {
162 if (!data) return false
163 return getNextPageParam(options, data) != null
165​
166/**
167 * Checks if there is a previous page.
168 */
169export function hasPreviousPage(
170 options: InfiniteQueryPageParamsOptions<any, any>,
171 data?: InfiniteData<unknown>,
172): boolean {
173 if (!data || !options.getPreviousPageParam) return false
174 return getPreviousPageParam(options, data) != null