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

useIsFetching.ts

159 lines3.9 KB

1import type { QueryClient, QueryFilters } from '@tanstack/query-core'
2import type { ReactiveControllerHost } from 'lit'
3import {
4 createValueAccessor,
5 readAccessor,
6 type Accessor,
7 type ValueAccessor,
8} from './accessor.js'
9import { BaseController } from './controllers/BaseController.js'
10​
11/**
12 * Accessor returned by `useIsFetching`.
13 *
14 * Call the accessor or read its `current` property to get the number of
15 * currently fetching queries that match the filters.
16 */
17export type IsFetchingAccessor = ValueAccessor<number> & { destroy: () => void }
18​
19class IsFetchingController extends BaseController<number> {
20 private queryClient: QueryClient | undefined
21 private unsubscribe: (() => void) | undefined
22​
23 constructor(
24 host: ReactiveControllerHost,
25 private readonly filters: Accessor<QueryFilters> = {},
26 queryClient?: QueryClient,
27 ) {
28 super(host, 0, queryClient)
29​
30 if (!queryClient) {
31 return
32 }
33​
34 this.queryClient = queryClient
35 this.result = this.computeValue()
36 }
37​
38 protected onConnected(): void {
39 if (!this.syncClient()) {
40 this.setResult(0)
41 return
42 }
43​
44 this.subscribe()
45 this.setResult(this.computeValue())
46 }
47​
48 protected onDisconnected(): void {
49 this.unsubscribe?.()
50 this.unsubscribe = undefined
51 this.syncClient()
52 }
53​
54 protected onHostUpdate(): void {
55 if (typeof this.filters !== 'function') {
56 return
57 }
58​
59 this.setResult(this.syncClient() ? this.computeValue() : 0)
60 }
61​
62 protected onQueryClientChanged(): void {
63 if (!this.syncClient()) {
64 this.setResult(0)
65 return
66 }
67​
68 if (this.connectedState) {
69 this.subscribe()
70 this.setResult(this.computeValue())
71 }
72 }
73​
74 private syncClient(): boolean {
75 const nextClient = this.tryGetQueryClient()
76 if (!nextClient) {
77 this.unsubscribe?.()
78 this.unsubscribe = undefined
79 this.queryClient = undefined
80 return false
81 }
82​
83 if (nextClient === this.queryClient) {
84 return true
85 }
86​
87 this.unsubscribe?.()
88 this.unsubscribe = undefined
89 this.queryClient = nextClient
90 return true
91 }
92​
93 private subscribe(): void {
94 if (!this.queryClient) {
95 return
96 }
97​
98 if (this.unsubscribe) {
99 return
100 }
101​
102 this.unsubscribe = this.queryClient.getQueryCache().subscribe(() => {
103 this.setResult(this.computeValue())
104 })
105 }
106​
107 private computeValue(): number {
108 if (!this.queryClient) {
109 return 0
110 }
111​
112 return this.queryClient.isFetching(readAccessor(this.filters))
113 }
115​
116/**
117 * Creates a Lit reactive controller that tracks how many matching queries are
118 * currently fetching.
119 *
120 * When `filters` is a function, it is re-read during host updates so the count
121 * can follow reactive host state. If `queryClient` is omitted, the controller
122 * resolves the client from the nearest connected `QueryClientProvider`.
123 *
124 * @param host - The Lit reactive controller host that owns the cache
125 * subscription.
126 * @param filters - Query filters, or a getter that returns query filters.
127 * @param queryClient - Optional explicit query client. Provide this for
128 * controllers that should not resolve a client from Lit context.
129 * @returns An accessor for the current number of matching fetching queries.
130 *
131 * @example
132 * ```ts
133 * import { LitElement, html } from 'lit'
134 * import { useIsFetching } from '@tanstack/lit-query'
135 *
136 * class TodosStatus extends LitElement {
137 * private readonly todosFetching = useIsFetching(this, {
138 * queryKey: ['todos'],
139 * })
140 *
141 * render() {
142 * return html`<span>${this.todosFetching()} active todo fetches</span>`
143 * }
144 * }
145 * ```
146 */
147export function useIsFetching(
148 host: ReactiveControllerHost,
149 filters: Accessor<QueryFilters> = {},
150 queryClient?: QueryClient,
151): IsFetchingAccessor {
152 const controller = new IsFetchingController(host, filters, queryClient)
153 return Object.assign(
154 createValueAccessor(() => controller.current),
155 {
156 destroy: () => controller.destroy(),
157 },
158 )