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

createMutationController.ts

349 lines9.1 KB

1import { MutationObserver } from '@tanstack/query-core'
2import { createValueAccessor, readAccessor } from './accessor.js'
3import { createMissingQueryClientError } from './context.js'
4import { BaseController } from './controllers/BaseController.js'
5import type {
6 DefaultError,
7 MutateFunction,
8 MutationObserverOptions,
9 MutationObserverResult,
10 QueryClient,
11} from '@tanstack/query-core'
12import type { ReactiveControllerHost } from 'lit'
13import type { Accessor, ValueAccessor } from './accessor.js'
14​
15/**
16 * Options accepted by `createMutationController`.
17 *
18 * This is the Lit adapter shape for `MutationObserverOptions`. Pass it directly
19 * or through an `Accessor` when the options depend on Lit host state.
20 */
21export type CreateMutationOptions<
22 TData = unknown,
23 TError = DefaultError,
24 TVariables = void,
25 TOnMutateResult = unknown,
26> = MutationObserverOptions<TData, TError, TVariables, TOnMutateResult>
27​
28/**
29 * Accessor returned by `createMutationController`.
30 *
31 * Call the accessor or read its `current` property to get the latest mutation
32 * result. The attached methods delegate to the active mutation observer.
33 */
34export type MutationResultAccessor<TData, TError, TVariables, TOnMutateResult> =
35 ValueAccessor<
36 MutationObserverResult<TData, TError, TVariables, TOnMutateResult>
37 > & {
38 /**
39 * Starts the mutation and swallows the returned promise.
40 *
41 * Throws synchronously if no `QueryClient` can be resolved.
42 */
43 mutate: (
44 ...args: Parameters<
45 MutateFunction<TData, TError, TVariables, TOnMutateResult>
46 >
47 ) => void
48 /**
49 * Starts the mutation and returns the observer promise.
50 *
51 * Rejects if no `QueryClient` can be resolved.
52 */
53 mutateAsync: MutationObserverResult<
54 TData,
55 TError,
56 TVariables,
57 TOnMutateResult
58 >['mutate']
59 /** Resets the mutation observer to its idle state. */
60 reset: MutationObserverResult<
61 TData,
62 TError,
63 TVariables,
64 TOnMutateResult
65 >['reset']
66 /** Removes the controller from its Lit host and unsubscribes observers. */
67 destroy: () => void
68 }
69​
70/**
71 * Returns the result used while no `QueryClient` is available: `'idle'`, with a `mutate` that
72 * rejects with the missing client error.
73 * @returns A new result object in that state.
74 */
75function createIdleMutationResult<
76 TData,
77 TError,
78 TVariables,
79 TOnMutateResult,
80>(): MutationObserverResult<TData, TError, TVariables, TOnMutateResult> {
81 return {
82 context: undefined,
83 data: undefined,
84 error: null,
85 failureCount: 0,
86 failureReason: null,
87 isError: false,
88 isIdle: true,
89 isPending: false,
90 isPaused: false,
91 isSuccess: false,
92 status: 'idle',
93 submittedAt: 0,
94 variables: undefined,
95 mutate: () => Promise.reject(createMissingQueryClientError()),
96 reset: () => undefined,
97 }
99​
100class MutationController<
101 TData,
102 TError,
103 TVariables,
104 TOnMutateResult,
105> extends BaseController<
106 MutationObserverResult<TData, TError, TVariables, TOnMutateResult>
107> {
108 private readonly options: Accessor<
109 CreateMutationOptions<TData, TError, TVariables, TOnMutateResult>
110 >
111 private observer:
112 | MutationObserver<TData, TError, TVariables, TOnMutateResult>
113 | undefined
114 private unsubscribe: (() => void) | undefined
115 private queryClient: QueryClient | undefined
116​
117 constructor(
118 host: ReactiveControllerHost,
119 options: Accessor<
120 CreateMutationOptions<TData, TError, TVariables, TOnMutateResult>
121 >,
122 queryClient?: QueryClient,
123 ) {
124 super(host, createIdleMutationResult(), queryClient)
125 this.options = options
126​
127 if (!queryClient) {
128 return
129 }
130​
131 if (typeof options === 'function') {
132 return
133 }
134​
135 const observer = new MutationObserver(
136 queryClient,
137 this.defaultOptions(queryClient),
138 )
139 this.queryClient = queryClient
140 this.observer = observer
141 this.result = observer.getCurrentResult()
142 }
143​
144 protected override onConnected(): void {
145 if (!this.syncClient()) {
146 return
147 }
148​
149 this.refreshOptions()
150 this.subscribe()
151 if (this.observer) {
152 this.setResult(this.observer.getCurrentResult())
153 }
154 }
155​
156 protected override onDisconnected(): void {
157 this.unsubscribeObserver()
158 this.syncClient()
159 }
160​
161 protected override onHostUpdate(): void {
162 if (typeof this.options !== 'function') {
163 return
164 }
165​
166 this.refreshOptions()
167 }
168​
169 protected override onQueryClientChanged(): void {
170 if (!this.syncClient() || !this.connectedState) {
171 return
172 }
173​
174 this.refreshOptions()
175 this.subscribe()
176 if (this.observer) {
177 this.setResult(this.observer.getCurrentResult())
178 }
179 }
180​
181 mutate = (
182 ...args: Parameters<
183 MutateFunction<TData, TError, TVariables, TOnMutateResult>
184 >
185 ): void => {
186 if (!this.syncClient() || !this.observer) {
187 throw createMissingQueryClientError()
188 }
189​
190 void this.observer.mutate(args[0] as TVariables, args[1]).catch(() => {
191 // Intentionally swallow in sync mutate path.
192 })
193 }
194​
195 mutateAsync: MutationObserverResult<
196 TData,
197 TError,
198 TVariables,
199 TOnMutateResult
200 >['mutate'] = (...args) => {
201 if (!this.syncClient() || !this.observer) {
202 return Promise.reject(createMissingQueryClientError())
203 }
204​
205 return this.observer.mutate(args[0] as TVariables, args[1])
206 }
207​
208 reset: MutationObserverResult<
209 TData,
210 TError,
211 TVariables,
212 TOnMutateResult
213 >['reset'] = () => {
214 if (!this.syncClient() || !this.observer) {
215 return
216 }
217​
218 this.observer.reset()
219 this.setResult(this.observer.getCurrentResult())
220 }
221​
222 private subscribe(): void {
223 if (!this.observer) {
224 return
225 }
226​
227 if (this.unsubscribe) {
228 return
229 }
230​
231 this.unsubscribe = this.observer.subscribe((next) => {
232 this.setResult(next)
233 })
234 }
235​
236 private unsubscribeObserver(): void {
237 this.unsubscribe?.()
238 this.unsubscribe = undefined
239 }
240​
241 private syncClient(): boolean {
242 const nextClient = this.tryGetQueryClient()
243 if (!nextClient) {
244 this.unsubscribeObserver()
245 this.queryClient = undefined
246 this.observer = undefined
247 this.setResult(createIdleMutationResult())
248 return false
249 }
250​
251 if (nextClient === this.queryClient) {
252 return true
253 }
254​
255 this.unsubscribeObserver()
256 this.queryClient = nextClient
257 this.observer = new MutationObserver(
258 this.queryClient,
259 this.defaultOptions(this.queryClient),
260 )
261 this.setResult(this.observer.getCurrentResult())
262 return true
263 }
264​
265 private refreshOptions(): boolean {
266 if (!this.syncClient() || !this.observer || !this.queryClient) {
267 return false
268 }
269​
270 this.observer.setOptions(this.defaultOptions())
271 this.setResult(this.observer.getCurrentResult())
272 return true
273 }
274​
275 private defaultOptions(
276 client = this.queryClient,
277 ): MutationObserverOptions<TData, TError, TVariables, TOnMutateResult> {
278 if (!client) {
279 throw createMissingQueryClientError()
280 }
281​
282 return client.defaultMutationOptions(readAccessor(this.options))
283 }
285​
286/**
287 * Creates a Lit reactive controller that subscribes the host to a mutation.
288 *
289 * The returned accessor is callable and also exposes `current`, `mutate`,
290 * `mutateAsync`, `reset`, and `destroy`. When `options` is a function, it is
291 * re-read during host updates so mutation options can follow reactive host
292 * state.
293 *
294 * If `queryClient` is omitted, the controller resolves the client from the
295 * nearest connected `QueryClientProvider`.
296 * @param host - The Lit reactive controller host that owns the mutation
297 * subscription.
298 * @param options - Mutation observer options, or a getter that returns options.
299 * @param queryClient - Optional explicit query client. Provide this for
300 * controllers that should not resolve a client from Lit context.
301 * @returns An accessor for the latest mutation result with mutation helper
302 * methods.
303 * @example
304 * ```ts
305 * import { LitElement, html } from 'lit'
306 * import { createMutationController } from '@tanstack/lit-query'
307 *
308 * class AddTodoForm extends LitElement {
309 * private readonly addTodo = createMutationController(this, {
310 * mutationFn: (title: string) =>
311 * fetch('/api/todos', { method: 'POST', body: JSON.stringify({ title }) }),
312 * })
313 *
314 * render() {
315 * const mutation = this.addTodo()
316 *
317 * return html`
318 * <button ?disabled=${mutation.isPending} @click=${() => this.addTodo.mutate('Ship docs')}>
319 * Add todo
320 * </button>
321 * `
322 * }
323 * }
324 * ```
325 */
326export function createMutationController<
327 TData = unknown,
328 TError = DefaultError,
329 TVariables = void,
330 TOnMutateResult = unknown,
331>(
332 host: ReactiveControllerHost,
333 options: Accessor<
334 CreateMutationOptions<TData, TError, TVariables, TOnMutateResult>
335 >,
336 queryClient?: QueryClient,
337): MutationResultAccessor<TData, TError, TVariables, TOnMutateResult> {
338 const controller = new MutationController(host, options, queryClient)
339​
340 return Object.assign(
341 createValueAccessor(() => controller.current),
342 {
343 mutate: controller.mutate,
344 mutateAsync: controller.mutateAsync,
345 reset: controller.reset,
346 destroy: () => controller.destroy(),
347 },
348 )