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

createMutationController.md

100 lines2.6 KB

1---
2id: createMutationController
3title: createMutationController
4---
5​
6```ts
7function createMutationController<TData, TError, TVariables, TOnMutateResult>(
8 host: ReactiveControllerHost,
9 options: Accessor<CreateMutationOptions<TData, TError, TVariables, TOnMutateResult>>,
10queryClient?: QueryClient): MutationResultAccessor<TData, TError, TVariables, TOnMutateResult>;
11```
12​
13Defined in: [packages/lit-query/src/createMutationController.ts:325](https://github.com/TanStack/query/blob/main/packages/lit-query/src/createMutationController.ts#L325)
14​
15Creates a Lit reactive controller that subscribes the host to a mutation.
16​
17The returned accessor is callable and also exposes `current`, `mutate`,
18`mutateAsync`, `reset`, and `destroy`. When `options` is a function, it is
19re-read during host updates so mutation options can follow reactive host
20state.
21​
22If `queryClient` is omitted, the controller resolves the client from the
23nearest connected `QueryClientProvider`.
24​
25## Type Parameters
26​
27### TData
28​
29`TData` = `unknown`
30​
31### TError
32​
33`TError` = `Error`
34​
35### TVariables
36​
37`TVariables` = `void`
38​
39### TOnMutateResult
40​
41`TOnMutateResult` = `unknown`
42​
43## Parameters
44​
45### host
46​
47`ReactiveControllerHost`
48​
49The Lit reactive controller host that owns the mutation
50subscription.
51​
52### options
53​
54[`Accessor`](../type-aliases/Accessor.md)\<[`CreateMutationOptions`](../type-aliases/CreateMutationOptions.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>\>
55​
56Mutation observer options, or a getter that returns options.
57​
58<a id="options-properties"></a>
59​
60#### `options` properties
61​
62Built from [`MutationObserverOptions`](../interfaces/MutationObserverOptions.md#properties). See the type above for what it changes.
63​
64### queryClient?
65​
66[`QueryClient`](../classes/QueryClient.md)
67​
68Optional explicit query client. Provide this for
69controllers that should not resolve a client from Lit context.
70​
71## Returns
72​
73[`MutationResultAccessor`](../type-aliases/MutationResultAccessor.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>
74​
75An accessor for the latest mutation result with mutation helper
76methods.
77​
78## Example
79​
80```ts
81import { LitElement, html } from 'lit'
82import { createMutationController } from '@tanstack/lit-query'
83​
84class AddTodoForm extends LitElement {
85 private readonly addTodo = createMutationController(this, {
86 mutationFn: (title: string) =>
87 fetch('/api/todos', { method: 'POST', body: JSON.stringify({ title }) }),
88 })
89​
90 render() {
91 const mutation = this.addTodo()
92​
93 return html`
94 <button ?disabled=${mutation.isPending} @click=${() => this.addTodo.mutate('Ship docs')}>
95 Add todo
96 </button>
97 `
98 }
100```