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

createMutationController.md

94 lines2.3 KB

1---
2id: createMutationController
3title: createMutationController
4---
5​
6```ts
7function createMutationController<TData, TError, TVariables, TOnMutateResult>(
8 host,
9 options,
10queryClient?): MutationResultAccessor<TData, TError, TVariables, TOnMutateResult>;
11```
12​
13Defined in: [packages/lit-query/src/createMutationController.ts:338](https://github.com/TanStack/query/blob/main/packages/lit-query/src/createMutationController.ts#L338)
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### queryClient?
59​
60`QueryClient`
61​
62Optional explicit query client. Provide this for
63controllers that should not resolve a client from Lit context.
64​
65## Returns
66​
67[`MutationResultAccessor`](../type-aliases/MutationResultAccessor.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>
68​
69An accessor for the latest mutation result with mutation helper
70methods.
71​
72## Example
73​
74```ts
75import { LitElement, html } from 'lit'
76import { createMutationController } from '@tanstack/lit-query'
77​
78class AddTodoForm extends LitElement {
79 private readonly addTodo = createMutationController(this, {
80 mutationFn: (title: string) =>
81 fetch('/api/todos', { method: 'POST', body: JSON.stringify({ title }) }),
82 })
83​
84 render() {
85 const mutation = this.addTodo()
86​
87 return html`
88 <button ?disabled=${mutation.isPending} @click=${() => this.addTodo.mutate('Ship docs')}>
89 Add todo
90 </button>
91 `
92 }
94```