Open History to see the last commit
1import { replaceEqualDeep } from '@tanstack/query-core'
2import { createValueAccessor, readAccessor } from './accessor.js'
3import { BaseController } from './controllers/BaseController.js'
4import type {
5 Mutation,
6 MutationFilters,
7 MutationState,
8 QueryClient,
9} from '@tanstack/query-core'
10import type { ReactiveControllerHost } from 'lit'
11import type { Accessor, ValueAccessor } from './accessor.js'
12β
13/**
14 * Options accepted by `useMutationState`.
15 */
16export type MutationStateOptions<TResult> = {
17 /** Filters used to select mutations from the mutation cache. */
18 filters?: Accessor<MutationFilters>
19 /** Maps each matching mutation to the value returned by the accessor. */
20 select?: (mutation: Mutation) => TResult
21}
22β
23/**
24 * Accessor returned by `useMutationState`.
25 *
26 * Call the accessor or read its `current` property to get the selected state for
27 * matching mutations.
28 */
29export type MutationStateAccessor<TResult> = ValueAccessor<Array<TResult>> & {
30 /** Removes the controller from its Lit host and unsubscribes observers. */
31 destroy: () => void
32}
33β
34class MutationStateController<TResult> extends BaseController<Array<TResult>> {
35 private queryClient: QueryClient | undefined
36 private unsubscribe: (() => void) | undefined
37β
38 constructor(
39 host: ReactiveControllerHost,
40 private readonly options: MutationStateOptions<TResult>,
41 queryClient?: QueryClient,
42 ) {
43 super(host, [], queryClient)
44β
45 if (!queryClient) {
46 return
47 }
48β
49 this.queryClient = queryClient
50 this.result = this.computeState()
51 }
52β
53 protected override onConnected(): void {
54 if (!this.syncClient()) {
55 this.setMutationState([])
56 return
57 }
58β
59 this.subscribe()
60 this.setMutationState(this.computeState())
61 }
62β
63 protected override onDisconnected(): void {
64 this.unsubscribe?.()
65 this.unsubscribe = undefined
66 this.syncClient()
67 }
68β
69 protected override onHostUpdate(): void {
70 if (!this.shouldRefreshOnHostUpdate()) {
71 return
72 }
73β
74 this.setMutationState(this.syncClient() ? this.computeState() : [])
75 }
76β
77 protected override onQueryClientChanged(): void {
78 if (!this.syncClient()) {
79 this.setMutationState([])
80 return
81 }
82β
83 if (this.connectedState) {
84 this.subscribe()
85 this.setMutationState(this.computeState())
86 }
87 }
88β
89 private syncClient(): boolean {
90 const nextClient = this.tryGetQueryClient()
91 if (!nextClient) {
92 this.unsubscribe?.()
93 this.unsubscribe = undefined
94 this.queryClient = undefined
95 return false
96 }
97β
98 if (nextClient === this.queryClient) {
99 return true
100 }
101β
102 this.unsubscribe?.()
103 this.unsubscribe = undefined
104 this.queryClient = nextClient
105 return true
106 }
107β
108 private subscribe(): void {
109 if (!this.queryClient) {
110 return
111 }
112β
113 if (this.unsubscribe) {
114 return
115 }
116β
117 this.unsubscribe = this.queryClient.getMutationCache().subscribe(() => {
118 this.setMutationState(this.computeState())
119 })
120 }
121β
122 private setMutationState(next: Array<TResult>): void {
123 this.setResult(replaceEqualDeep(this.result, next))
124 }
125β
126 private shouldRefreshOnHostUpdate(): boolean {
127 return (
128 typeof this.options.filters === 'function' ||
129 typeof this.options.select === 'function'
130 )
131 }
132β
133 private computeState(): Array<TResult> {
134 if (!this.queryClient) {
135 return []
136 }
137β
138 const filters = this.options.filters
139 ? readAccessor(this.options.filters)
140 : undefined
141β
142 const select = this.options.select
143 const mutations = this.queryClient.getMutationCache().findAll(filters)
144β
145 return mutations.map((mutation) => {
146 if (select) {
147 return select(mutation)
148 }
149β
150 return mutation.state as TResult
151 })
152 }
153}
154β
155/**
156 * Creates a Lit reactive controller that selects state from matching mutations
157 * in the mutation cache.
158 *
159 * When `options.filters` is a function, it is re-read during host updates so
160 * the selection can follow reactive host state. If `queryClient` is omitted,
161 * the controller resolves the client from the nearest connected
162 * `QueryClientProvider`.
163 * @param host - The Lit reactive controller host that owns the mutation cache
164 * subscription.
165 * @param options - Mutation state filters and optional selector.
166 * @param queryClient - Optional explicit query client. Provide this for
167 * controllers that should not resolve a client from Lit context.
168 * @returns An accessor for the selected mutation state array.
169 * @example
170 * ```ts
171 * import { LitElement, html } from 'lit'
172 * import { useMutationState } from '@tanstack/lit-query'
173 *
174 * class PendingUploads extends LitElement {
175 * private readonly uploads = useMutationState(this, {
176 * filters: { mutationKey: ['upload'], status: 'pending' },
177 * select: (mutation) => mutation.state.variables as File,
178 * })
179 *
180 * render() {
181 * return html`<span>${this.uploads().length} uploads pending</span>`
182 * }
183 * }
184 * ```
185 */
186export function useMutationState<
187 TResult = MutationState<unknown, unknown, unknown, unknown>,
188>(
189 host: ReactiveControllerHost,
190 options: MutationStateOptions<TResult> = {},
191 queryClient?: QueryClient,
192): MutationStateAccessor<TResult> {
193 const controller = new MutationStateController(host, options, queryClient)
194 return Object.assign(
195 createValueAccessor(() => controller.current),
196 {
197 destroy: () => controller.destroy(),
198 },
199 )
200}