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

useMutationState.ts

202 lines5.3 KB

1import { replaceEqualDeep } from '@tanstack/query-core'
2import { createValueAccessor, readAccessor } from './accessor.js'
3import { BaseController } from './controllers/BaseController.js'
4import type { Accessor, ValueAccessor } from './accessor.js'
5import type {
6 Mutation,
7 MutationFilters,
8 MutationState,
9 QueryClient,
10} from '@tanstack/query-core'
11import type { ReactiveControllerHost } from 'lit'
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
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
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 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 onDisconnected(): void {
64 this.unsubscribe?.()
65 this.unsubscribe = undefined
66 this.syncClient()
67 }
68​
69 protected onHostUpdate(): void {
70 if (!this.shouldRefreshOnHostUpdate()) {
71 return
72 }
73​
74 this.setMutationState(this.syncClient() ? this.computeState() : [])
75 }
76​
77 protected 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 }
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 *
164 * @param host - The Lit reactive controller host that owns the mutation cache
165 * subscription.
166 * @param options - Mutation state filters and optional selector.
167 * @param queryClient - Optional explicit query client. Provide this for
168 * controllers that should not resolve a client from Lit context.
169 * @returns An accessor for the selected mutation state array.
170 *
171 * @example
172 * ```ts
173 * import { LitElement, html } from 'lit'
174 * import { useMutationState } from '@tanstack/lit-query'
175 *
176 * class PendingUploads extends LitElement {
177 * private readonly uploads = useMutationState(this, {
178 * filters: { mutationKey: ['upload'], status: 'pending' },
179 * select: (mutation) => mutation.state.variables as File,
180 * })
181 *
182 * render() {
183 * return html`<span>${this.uploads().length} uploads pending</span>`
184 * }
185 * }
186 * ```
187 */
188export function useMutationState<
189 TResult = MutationState<unknown, unknown, unknown, unknown>,
190>(
191 host: ReactiveControllerHost,
192 options: MutationStateOptions<TResult> = {},
193 queryClient?: QueryClient,
194): MutationStateAccessor<TResult> {
195 const controller = new MutationStateController(host, options, queryClient)
196 return Object.assign(
197 createValueAccessor(() => controller.current),
198 {
199 destroy: () => controller.destroy(),
200 },
201 )