Open History to see the last commit
1---
2id: mutations
3title: Mutations
4---
5β
6Unlike queries, mutations are used to create, update, delete, or otherwise perform server side effects. In Lit, use [`createMutationController`](../reference/functions/createMutationController.md).
7β
8```ts
9import { LitElement, html } from 'lit'
10import {
11 QueryClient,
12 QueryClientProvider,
13 createMutationController,
14 createQueryController,
15} from '@tanstack/lit-query'
16β
17const queryClient = new QueryClient()
18β
19class AppQueryProvider extends QueryClientProvider {
20 constructor() {
21 super()
22 this.client = queryClient
23 }
24}
25β
26customElements.define('app-query-provider', AppQueryProvider)
27β
28class TodosView extends LitElement {
29 private readonly todos = createQueryController(this, {
30 queryKey: ['todos'],
31 queryFn: fetchTodos,
32 })
33β
34 private readonly addTodo = createMutationController(this, {
35 mutationFn: createTodo,
36 onSuccess: async () => {
37 await queryClient.invalidateQueries({ queryKey: ['todos'] })
38 },
39 })
40β
41 render() {
42 const query = this.todos()
43 const mutation = this.addTodo()
44 const todos = query.data ?? []
45β
46 return html`
47 ${mutation.isError ? html`<p>${mutation.error.message}</p>` : null}
48 ${mutation.isSuccess ? html`<p>Todo added</p>` : null}
49β
50 <button
51 ?disabled=${mutation.isPending}
52 @click=${() => this.addTodo.mutate({ title: 'Write mutation docs' })}
53 >
54 ${mutation.isPending ? 'Adding...' : 'Add Todo'}
55 </button>
56β
57 <ul>
58 ${todos.map((todo) => html`<li>${todo.title}</li>`)}
59 </ul>
60 `
61 }
62}
63β
64customElements.define('todos-view', TodosView)
65```
66β
67Render the element under the provider so the controllers can resolve the same `QueryClient` from Lit context:
68β
69```html
70<app-query-provider>
71 <todos-view></todos-view>
72</app-query-provider>
73```
74β
75## Mutation States
76β
77A mutation can be in one of these primary states:
78β
79- `isIdle` or `status === 'idle'`: no mutation has run or it has been reset
80- `isPending` or `status === 'pending'`: the mutation is running
81- `isError` or `status === 'error'`: the mutation failed and `error` is available
82- `isSuccess` or `status === 'success'`: the mutation finished and `data` is available
83β
84## Variables
85β
86Pass variables to the mutation function by calling `mutate`:
87β
88```ts
89this.addTodo.mutate({
90 title: this.nextTitle,
91})
92```
93β
94`mutate` throws synchronously if the controller cannot resolve a `QueryClient`, such as when the element is not under a connected `QueryClientProvider` and no explicit client was passed. `mutateAsync` reports the same setup problem as a rejected promise.
95β
96Use `mutateAsync` when you want a promise:
97β
98```ts
99try {
100 const created = await this.addTodo.mutateAsync({ title: this.nextTitle })
101 this.nextTitle = created.title
102} catch (error) {
103 this.errorMessage = String(error)
104}
105```
106β
107## Resetting Mutation State
108β
109The accessor includes `reset`:
110β
111```ts
112html`
113 ${mutation.isError
114 ? html`<button @click=${() => this.addTodo.reset()}>Clear error</button>`
115 : null}
116`
117```
118β
119## Side Effects
120β
121Mutation options support `onMutate`, `onError`, `onSuccess`, and `onSettled`. The pagination example passes an explicit `queryClient` to the controller and uses the same in-scope client for optimistic updates and rollback:
122β
123```ts
124private readonly favoriteMutation = createMutationController(
125 this,
126 {
127 mutationKey: ['toggle-project-favorite'],
128 mutationFn: async (input) => {
129 const response = await toggleProjectFavoriteOnServer(input)
130 return response.project
131 },
132 onMutate: async (variables) => {
133 await queryClient.cancelQueries({ queryKey: ['projects'] })
134 const snapshots = queryClient.getQueriesData<ProjectsPageResponse>({
135 queryKey: ['projects'],
136 })
137β
138 for (const [key, existing] of snapshots) {
139 if (!existing) continue
140β
141 queryClient.setQueryData<ProjectsPageResponse>(key, {
142 ...existing,
143 projects: existing.projects.map((project) =>
144 project.id === variables.id
145 ? { ...project, isFavorite: variables.isFavorite }
146 : project,
147 ),
148 })
149 }
150β
151 return { snapshots }
152 },
153 onError: (_error, _variables, context) => {
154 for (const [key, snapshot] of context?.snapshots ?? []) {
155 queryClient.setQueryData(key, snapshot)
156 }
157 },
158 onSettled: async () => {
159 await queryClient.invalidateQueries({ queryKey: ['projects'] })
160 },
161 },
162 queryClient,
163)
164```
165β
166For the exact runnable flow, see the [Pagination example](../examples/pagination).