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

infiniteQueryBehavior.ts

166 lines4.7 KB

1import type { QueryBehavior } from './query'
2import { addToEnd, addToStart } from './utils'
3import type {
4 InfiniteData,
5 InfiniteQueryPageParamsOptions,
6 QueryFunctionContext,
7 QueryKey,
8} from './types'
9​
10export function infiniteQueryBehavior<TQueryFnData, TError, TData>(
11 pages?: number,
12): QueryBehavior<TQueryFnData, TError, InfiniteData<TData>> {
13 return {
14 onFetch: (context) => {
15 context.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 (typeof param === 'undefined' && 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.defaultPageParam,
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 },
118 }
120​
121function getNextPageParam(
122 options: InfiniteQueryPageParamsOptions<any>,
123 { pages, pageParams }: InfiniteData<unknown>,
124): unknown | undefined {
125 const lastIndex = pages.length - 1
126 return options.getNextPageParam(
127 pages[lastIndex],
128 pages,
129 pageParams[lastIndex],
130 pageParams,
131 )
133​
134function getPreviousPageParam(
135 options: InfiniteQueryPageParamsOptions<any>,
136 { pages, pageParams }: InfiniteData<unknown>,
137): unknown | undefined {
138 return options.getPreviousPageParam?.(
139 pages[0],
140 pages,
141 pageParams[0],
142 pageParams,
143 )
145​
146/**
147 * Checks if there is a next page.
148 */
149export function hasNextPage(
150 options: InfiniteQueryPageParamsOptions<any, any>,
151 data?: InfiniteData<unknown>,
152): boolean {
153 if (!data) return false
154 return typeof getNextPageParam(options, data) !== 'undefined'
156​
157/**
158 * Checks if there is a previous page.
159 */
160export function hasPreviousPage(
161 options: InfiniteQueryPageParamsOptions<any, any>,
162 data?: InfiniteData<unknown>,
163): boolean {
164 if (!data || !options.getPreviousPageParam) return false
165 return typeof getPreviousPageParam(options, data) !== 'undefined'