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