Open History to see the last commit
1---
2id: useMutation
3title: useMutation
4redirect_from:
5 - framework/solid/reference/useMutation
6---
7β
8```ts
9function useMutation<TData, TError, TVariables, TOnMutateResult>(options: UseMutationOptions<TData, TError, TVariables, TOnMutateResult>, queryClient?: Accessor<QueryClient>): UseMutationResult<TData, TError, TVariables, TOnMutateResult>;
10```
11β
12Defined in: [packages/solid-query/src/useMutation.ts:170](https://github.com/TanStack/query/blob/main/packages/solid-query/src/useMutation.ts#L170)
13β
14Unlike queries, mutations are typically used to create/update/delete data or perform server side-effects.
15`useMutation` is the primitive for that.
16β
17## Type Parameters
18β
19### TData
20β
21`TData` = `unknown`
22β
23### TError
24β
25`TError` = `Error`
26β
27### TVariables
28β
29`TVariables` = `void`
30β
31### TOnMutateResult
32β
33`TOnMutateResult` = `unknown`
34β
35## Parameters
36β
37### options
38β
39[`UseMutationOptions`](../type-aliases/UseMutationOptions.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>
40β
41An accessor returning the [UseMutationOptions](../type-aliases/UseMutationOptions.md) to use.
42β
43<a id="options-properties"></a>
44β
45#### `options` properties
46β
47Built from [`MutationOptions`](../interfaces/MutationOptions.md#properties). See the type above for what it changes.
48β
49### queryClient?
50β
51`Accessor`\<[`QueryClient`](../classes/QueryClient.md)\>
52β
53An accessor for a custom `QueryClient`. Otherwise, the one from the nearest context
54will be used.
55β
56## Returns
57β
58[`UseMutationResult`](../type-aliases/UseMutationResult.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>
59β
60`mutate`/`mutateAsync` also accept per-call `onSuccess`/`onError`/`onSettled` callbacks as a second
61argument, useful for triggering call-site side effects (e.g. navigation) without coupling them to the shared
62mutation definition. Hook-level callbacks (passed to `options`) fire for every mutation; per-call callbacks
63fire only for the latest call you've made, and only while the component is still mounted β unmounting before
64the mutation settles removes the subscription and prevents them from firing.
65β
66<a id="result-properties"></a>
67β
68### Result properties
69β
70Built from [`MutationObserverBaseResult`](../interfaces/MutationObserverBaseResult.md#properties). See the type above for what it changes.
71β
72## Examples
73β
74```tsx
75import { useMutation, useQueryClient } from '@tanstack/solid-query'
76β
77function TodoItem(props: { id: number }) {
78 const queryClient = useQueryClient()
79β
80 const deleteTodoMutation = useMutation(() => ({
81 mutationFn: deleteTodo,
82 onSuccess: () => {
83 queryClient.invalidateQueries({ queryKey: ['todos'] })
84 },
85 }))
86β
87 return (
88 <button onClick={() => deleteTodoMutation.mutate({ id: props.id })} disabled={deleteTodoMutation.isPending}>
89 Delete
90 </button>
91 )
92}
93```
94β
95Rendering the mutation's own state, rather than just firing it off:
96```tsx
97import { Match, Switch } from 'solid-js'
98import { useMutation, useQueryClient } from '@tanstack/solid-query'
99β
100function AddTodo() {
101 const queryClient = useQueryClient()
102β
103 const addMutation = useMutation(() => ({
104 mutationFn: addTodo,
105 onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
106 }))
107β
108 return (
109 <Switch fallback={<button onClick={() => addMutation.mutate('Item')}>Add</button>}>
110 <Match when={addMutation.isPending}>Adding todo...</Match>
111 <Match when={addMutation.isError}>
112 <div>An error occurred: {addMutation.error?.message}</div>
113 <button onClick={() => addMutation.mutate('Item')}>Add</button>
114 </Match>
115 </Switch>
116 )
117}
118```
119β
120Optimistic update via `onMutate`, rolling back on `onError`:
121```tsx
122import { useMutation, useQueryClient } from '@tanstack/solid-query'
123β
124function AddTodo() {
125 const queryClient = useQueryClient()
126β
127 const addMutation = useMutation(() => ({
128 mutationFn: addTodo,
129 onMutate: async (newTodo) => {
130 await queryClient.cancelQueries({ queryKey: ['todos'] })
131 const previousTodos = queryClient.getQueryData<Array<string>>(['todos'])
132β
133 queryClient.setQueryData<Array<string>>(['todos'], (old) => [
134 ...(old ?? []),
135 newTodo,
136 ])
137β
138 // Passed to `onError` as `onMutateResult` if the mutation fails.
139 return { previousTodos }
140 },
141 onError: (_err, _newTodo, onMutateResult) => {
142 queryClient.setQueryData(['todos'], onMutateResult?.previousTodos)
143 },
144 onSettled: () => {
145 queryClient.invalidateQueries({ queryKey: ['todos'] })
146 },
147 }))
148β
149 return (
150 <button onClick={() => addMutation.mutate('Item')}>Add</button>
151 )
152}
153```
154β
155Callbacks passed per call to `mutate` only fire for the last call β `mutateAsync` gives you a
156promise per call instead, so you can wait for all of them when they succeed:
157```tsx
158import { useMutation, useQueryClient } from '@tanstack/solid-query'
159β
160function AddTodos() {
161 const queryClient = useQueryClient()
162β
163 const addMutation = useMutation(() => ({
164 mutationFn: addTodo,
165 onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
166 }))
167β
168 async function handleAddAll(todos: Array<string>) {
169 try {
170 await Promise.all(todos.map((todo) => addMutation.mutateAsync(todo)))
171 } catch (error) {
172 console.error('Failed to add todos:', error)
173 }
174 }
175β
176 return (
177 <button onClick={() => handleAddAll(['Todo 1', 'Todo 2', 'Todo 3'])}>
178 Add all
179 </button>
180 )
181}
182```
183β
184If some of the mutations above can fail independently of the others, and you want to know which ones
185did β rather than losing that information the moment the first one rejects β swap `Promise.all` for
186`Promise.allSettled`:
187```tsx
188import { useMutation, useQueryClient } from '@tanstack/solid-query'
189β
190function AddTodos() {
191 const queryClient = useQueryClient()
192β
193 const addMutation = useMutation(() => ({
194 mutationFn: addTodo,
195 onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
196 }))
197β
198 async function handleAddAll(todos: Array<string>) {
199 const addResults = await Promise.allSettled(
200 todos.map((todo) => addMutation.mutateAsync(todo)),
201 )
202β
203 addResults.forEach((addResult, index) => {
204 if (addResult.status === 'rejected') {
205 console.error(`Failed to add "${todos[index]}":`, addResult.reason)
206 }
207 })
208 }
209β
210 return (
211 <button onClick={() => handleAddAll(['Todo 1', 'Todo 2', 'Todo 3'])}>
212 Add all
213 </button>
214 )
215}
216```