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

createInfiniteQueryController.ts

433 lines11.4 KB

1import {
2 InfiniteQueryObserver,
3 type DefaultError,
4 type DefaultedInfiniteQueryObserverOptions,
5 type InfiniteData,
6 type InfiniteQueryObserverOptions,
7 type InfiniteQueryObserverResult,
8 type QueryKey,
9} from '@tanstack/query-core'
10import type { QueryClient } from '@tanstack/query-core'
11import type { ReactiveControllerHost } from 'lit'
12import {
13 createValueAccessor,
14 readAccessor,
15 type Accessor,
16 type ValueAccessor,
17} from './accessor.js'
18import { createMissingQueryClientError } from './context.js'
19import { BaseController } from './controllers/BaseController.js'
20import { QueryObserverResultTracker } from './queryObserverResultTracker.js'
21​
22/**
23 * Options accepted by `createInfiniteQueryController`.
24 *
25 * This is the Lit adapter shape for `InfiniteQueryObserverOptions`. Pass it
26 * directly or through an `Accessor` when the options depend on Lit host state.
27 */
28export type CreateInfiniteQueryOptions<
29 TQueryFnData = unknown,
30 TError = DefaultError,
31 TData = InfiniteData<TQueryFnData>,
32 TQueryKey extends QueryKey = QueryKey,
33 TPageParam = unknown,
34> = InfiniteQueryObserverOptions<
35 TQueryFnData,
36 TError,
37 TData,
38 TQueryKey,
39 TPageParam
41​
42/**
43 * Accessor returned by `createInfiniteQueryController`.
44 *
45 * Call the accessor or read its `current` property to get the latest infinite
46 * query result. The attached methods delegate to the active infinite query
47 * observer.
48 */
49export type InfiniteQueryResultAccessor<TData, TError> = ValueAccessor<
50 InfiniteQueryObserverResult<TData, TError>
51> & {
52 /** Refetches the current infinite query. */
53 refetch: InfiniteQueryObserverResult<TData, TError>['refetch']
54 /** Fetches the next page for the current infinite query. */
55 fetchNextPage: InfiniteQueryObserverResult<TData, TError>['fetchNextPage']
56 /** Fetches the previous page for the current infinite query. */
57 fetchPreviousPage: InfiniteQueryObserverResult<
58 TData,
59 TError
60 >['fetchPreviousPage']
61 /** Removes the controller from its Lit host and unsubscribes observers. */
62 destroy: () => void
64​
65function createPendingInfiniteQueryResult<
66 TData,
67 TError,
68>(): InfiniteQueryObserverResult<TData, TError> {
69 return {
70 data: undefined,
71 dataUpdatedAt: 0,
72 error: null,
73 errorUpdatedAt: 0,
74 failureCount: 0,
75 failureReason: null,
76 errorUpdateCount: 0,
77 isError: false,
78 isFetched: false,
79 isFetchedAfterMount: false,
80 isFetching: false,
81 isInitialLoading: false,
82 isLoading: false,
83 isLoadingError: false,
84 isPaused: false,
85 isPending: true,
86 isPlaceholderData: false,
87 isRefetchError: false,
88 isRefetching: false,
89 isStale: true,
90 isEnabled: true,
91 isSuccess: false,
92 fetchStatus: 'idle',
93 status: 'pending',
94 refetch: (() =>
95 Promise.reject(
96 createMissingQueryClientError(),
97 )) as InfiniteQueryObserverResult<TData, TError>['refetch'],
98 fetchNextPage: (() =>
99 Promise.reject(
100 createMissingQueryClientError(),
101 )) as InfiniteQueryObserverResult<TData, TError>['fetchNextPage'],
102 fetchPreviousPage: (() =>
103 Promise.reject(
104 createMissingQueryClientError(),
105 )) as InfiniteQueryObserverResult<TData, TError>['fetchPreviousPage'],
106 hasNextPage: false,
107 hasPreviousPage: false,
108 isFetchNextPageError: false,
109 isFetchingNextPage: false,
110 isFetchPreviousPageError: false,
111 isFetchingPreviousPage: false,
112 promise: Promise.resolve(undefined as never),
113 } as unknown as InfiniteQueryObserverResult<TData, TError>
115​
116class InfiniteQueryController<
117 TQueryFnData,
118 TError,
119 TData,
120 TQueryKey extends QueryKey,
121 TPageParam,
122> extends BaseController<InfiniteQueryObserverResult<TData, TError>> {
123 private readonly options: Accessor<
124 CreateInfiniteQueryOptions<
125 TQueryFnData,
126 TError,
127 TData,
128 TQueryKey,
129 TPageParam
130 >
131 >
132 private observer:
133 | InfiniteQueryObserver<TQueryFnData, TError, TData, TQueryKey, TPageParam>
134 | undefined
135 private readonly resultTracker = new QueryObserverResultTracker<
136 InfiniteQueryObserverResult<TData, TError>
137 >()
138 private unsubscribe: (() => void) | undefined
139 private queryClient: QueryClient | undefined
140​
141 constructor(
142 host: ReactiveControllerHost,
143 options: Accessor<
144 CreateInfiniteQueryOptions<
145 TQueryFnData,
146 TError,
147 TData,
148 TQueryKey,
149 TPageParam
150 >
151 >,
152 queryClient?: QueryClient,
153 ) {
154 super(host, createPendingInfiniteQueryResult(), queryClient)
155 this.options = options
156​
157 if (!queryClient) {
158 return
159 }
160​
161 if (typeof options === 'function') {
162 return
163 }
164​
165 const defaulted = this.defaultOptions(queryClient)
166 const observer = new InfiniteQueryObserver(queryClient, defaulted)
167 this.queryClient = queryClient
168 this.observer = observer
169 this.assignObserverResult(observer.getOptimisticResult(defaulted))
170 }
171​
172 protected onConnected(): void {
173 if (!this.syncClient()) {
174 return
175 }
176​
177 this.refreshOptions()
178 this.subscribe()
179 this.observer?.updateResult()
180 if (this.observer) {
181 this.setObserverResult(this.observer.getCurrentResult())
182 }
183 }
184​
185 protected onDisconnected(): void {
186 this.unsubscribeObserver()
187 this.syncClient()
188 }
189​
190 protected onHostUpdate(): void {
191 if (typeof this.options !== 'function') {
192 return
193 }
194​
195 this.refreshOptions()
196 }
197​
198 protected onQueryClientChanged(): void {
199 if (!this.syncClient() || !this.connectedState) {
200 return
201 }
202​
203 this.refreshOptions()
204 this.subscribe()
205 this.observer?.updateResult()
206 if (this.observer) {
207 this.setObserverResult(this.observer.getCurrentResult())
208 }
209 }
210​
211 refetch: InfiniteQueryObserverResult<TData, TError>['refetch'] = (
212 ...args
213 ) => {
214 if (!this.applyOptions() || !this.observer) {
215 return Promise.reject(createMissingQueryClientError())
216 }
217​
218 return this.observer.refetch(...args)
219 }
220​
221 fetchNextPage: InfiniteQueryObserverResult<TData, TError>['fetchNextPage'] = (
222 ...args
223 ) => {
224 if (!this.applyOptions() || !this.observer) {
225 return Promise.reject(createMissingQueryClientError())
226 }
227​
228 return this.observer.fetchNextPage(...args)
229 }
230​
231 fetchPreviousPage: InfiniteQueryObserverResult<
232 TData,
233 TError
234 >['fetchPreviousPage'] = (...args) => {
235 if (!this.applyOptions() || !this.observer) {
236 return Promise.reject(createMissingQueryClientError())
237 }
238​
239 return this.observer.fetchPreviousPage(...args)
240 }
241​
242 readCurrent(): InfiniteQueryObserverResult<TData, TError> {
243 if (this.observer) {
244 this.assignObserverResult(this.observer.getCurrentResult())
245 }
246​
247 return this.current
248 }
249​
250 private subscribe(): void {
251 if (!this.observer) {
252 return
253 }
254​
255 if (this.unsubscribe) {
256 return
257 }
258​
259 this.unsubscribe = this.observer.subscribe((next) => {
260 this.setObserverResult(next)
261 })
262 }
263​
264 private unsubscribeObserver(): void {
265 this.unsubscribe?.()
266 this.unsubscribe = undefined
267 }
268​
269 private syncClient(): boolean {
270 const nextClient = this.tryGetQueryClient()
271 if (!nextClient) {
272 this.unsubscribeObserver()
273 this.queryClient = undefined
274 this.observer = undefined
275 this.resultTracker.reset()
276 this.setResult(createPendingInfiniteQueryResult())
277 return false
278 }
279​
280 if (nextClient === this.queryClient) {
281 return true
282 }
283​
284 this.unsubscribeObserver()
285 this.queryClient = nextClient
286 const options = this.defaultOptions(this.queryClient)
287 this.observer = new InfiniteQueryObserver(this.queryClient, options)
288 this.setObserverResult(this.observer.getOptimisticResult(options))
289 return true
290 }
291​
292 private applyOptions(): boolean {
293 if (!this.syncClient() || !this.observer || !this.queryClient) {
294 return false
295 }
296​
297 const options = this.defaultOptions(this.queryClient)
298 this.observer.setOptions(options)
299 return true
300 }
301​
302 private refreshOptions(): boolean {
303 if (!this.applyOptions() || !this.observer) {
304 return false
305 }
306​
307 this.setObserverResult(this.observer.getCurrentResult())
308 return true
309 }
310​
311 private assignObserverResult(
312 result: InfiniteQueryObserverResult<TData, TError>,
313 ): void {
314 const trackedResult = this.resultTracker.update(this.observer, result)
315 if (trackedResult) {
316 this.result = trackedResult
317 }
318 }
319​
320 private setObserverResult(
321 result: InfiniteQueryObserverResult<TData, TError>,
322 ): void {
323 const trackedResult = this.resultTracker.update(this.observer, result)
324 if (trackedResult) {
325 this.setResult(trackedResult)
326 }
327 }
328​
329 private defaultOptions(
330 client = this.queryClient,
331 ): DefaultedInfiniteQueryObserverOptions<
332 TQueryFnData,
333 TError,
334 TData,
335 TQueryKey,
336 TPageParam
337 > {
338 if (!client) {
339 throw createMissingQueryClientError()
340 }
341​
342 const defaulted = client.defaultQueryOptions(
343 readAccessor(this.options),
344 ) as DefaultedInfiniteQueryObserverOptions<
345 TQueryFnData,
346 TError,
347 TData,
348 TQueryKey,
349 TPageParam
350 >
351 ;(defaulted as { _optimisticResults?: 'optimistic' })._optimisticResults =
352 'optimistic'
353 return defaulted
354 }
356​
357/**
358 * Creates a Lit reactive controller that subscribes the host to an infinite
359 * query.
360 *
361 * The returned accessor is callable and also exposes `current`, `refetch`,
362 * `fetchNextPage`, `fetchPreviousPage`, and `destroy`. When `options` is a
363 * function, it is re-read during host updates so query keys and options can
364 * follow reactive host state.
365 *
366 * If `queryClient` is omitted, the controller resolves the client from the
367 * nearest connected `QueryClientProvider`.
368 *
369 * @param host - The Lit reactive controller host that owns the infinite query
370 * subscription.
371 * @param options - Infinite query observer options, or a getter that returns
372 * options.
373 * @param queryClient - Optional explicit query client. Provide this for
374 * controllers that should not resolve a client from Lit context.
375 * @returns An accessor for the latest infinite query result with page helper
376 * methods.
377 *
378 * @example
379 * ```ts
380 * import { LitElement, html } from 'lit'
381 * import { createInfiniteQueryController } from '@tanstack/lit-query'
382 *
383 * class ProjectsView extends LitElement {
384 * private readonly projects = createInfiniteQueryController(this, {
385 * queryKey: ['projects'],
386 * queryFn: ({ pageParam }) => fetchProjects(pageParam),
387 * initialPageParam: 0,
388 * getNextPageParam: (lastPage) => lastPage.nextCursor,
389 * })
390 *
391 * render() {
392 * const query = this.projects()
393 *
394 * return html`
395 * <button ?disabled=${!query.hasNextPage} @click=${() => this.projects.fetchNextPage()}>
396 * Load more
397 * </button>
398 * `
399 * }
400 * }
401 * ```
402 */
403export function createInfiniteQueryController<
404 TQueryFnData = unknown,
405 TError = DefaultError,
406 TData = InfiniteData<TQueryFnData>,
407 TQueryKey extends QueryKey = QueryKey,
408 TPageParam = unknown,
409>(
410 host: ReactiveControllerHost,
411 options: Accessor<
412 CreateInfiniteQueryOptions<
413 TQueryFnData,
414 TError,
415 TData,
416 TQueryKey,
417 TPageParam
418 >
419 >,
420 queryClient?: QueryClient,
421): InfiniteQueryResultAccessor<TData, TError> {
422 const controller = new InfiniteQueryController(host, options, queryClient)
423​
424 return Object.assign(
425 createValueAccessor(() => controller.readCurrent()),
426 {
427 refetch: controller.refetch,
428 fetchNextPage: controller.fetchNextPage,
429 fetchPreviousPage: controller.fetchPreviousPage,
430 destroy: () => controller.destroy(),
431 },
432 )