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