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