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

useMutationState.ts

206 lines5.2 KB

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