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