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