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

useMutation.md

208 lines5.9 KB

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