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