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

createInfiniteQueryController.ts

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