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

createInfiniteQueryController.ts

532 lines13.5 KB

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