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

mutations.md

164 lines4.4 KB

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 }
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 }
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)
105```
106​
107## Resetting Mutation State
108​
109The accessor includes `reset`:
110​
111```ts
112html`
113 ${
114 mutation.isError
115 ? html`<button @click=${() => this.addTodo.reset()}>Clear error</button>`
116 : null
117 }
119```
120​
121## Side Effects
122​
123Mutation 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. Its `mutationKey` and `mutationFn` come from the example's `projectsMutations.updateFavorite()`:
124​
125```ts
126private readonly favoriteMutation = createMutationController(
127 this,
128 {
129 ...projectsMutations.updateFavorite(),
130 onMutate: async (variables) => {
131 await queryClient.cancelQueries({ queryKey: projectsQueries.all() })
132 const snapshots = queryClient.getQueriesData<ProjectsPageResponse>({
133 queryKey: projectsQueries.all(),
134 })
135​
136 for (const [key, existing] of snapshots) {
137 if (!existing) continue
138​
139 queryClient.setQueryData<ProjectsPageResponse>(key, {
140 ...existing,
141 projects: existing.projects.map((project) =>
142 project.id === variables.id
143 ? { ...project, isFavorite: variables.isFavorite }
144 : project,
145 ),
146 })
147 }
148​
149 return { snapshots }
150 },
151 onError: (_error, _variables, onMutateResult) => {
152 for (const [key, snapshot] of onMutateResult?.snapshots ?? []) {
153 queryClient.setQueryData(key, snapshot)
154 }
155 },
156 onSettled: async () => {
157 await queryClient.invalidateQueries({ queryKey: projectsQueries.all() })
158 },
159 },
160 queryClient,
162```
163​
164For the exact runnable flow, see the [Pagination example](../examples/pagination).