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

createMutationController.md

96 lines2.3 KB

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