Open History to see the last commit
1import { MutationObserver, shouldThrowError } from '@tanstack/query-core'
2import {
3 computed,
4 getCurrentScope,
5 onScopeDispose,
6 reactive,
7 readonly,
8 shallowReactive,
9 shallowReadonly,
10 toRefs,
11 watch,
12} from 'vue-demi'
13import { useQueryClient } from './useQueryClient'
14import { cloneDeepUnref, updateState } from './utils'
15import type {
16 DefaultError,
17 DistributiveOmit,
18 MutateFunction,
19 MutationObserverResult,
20} from '@tanstack/query-core'
21import type { ToRefs } from 'vue-demi'
22import type { QueryClient } from './queryClient'
23import type { MaybeRefDeep, MutationOptions } from './types'
24β
25/**
26 * The {@link MutationObserverResult} properties without `mutate` and `reset`, which `useMutation` replaces with
27 * its own versions.
28 */
29export type MutationResult<TData, TError, TVariables, TOnMutateResult> =
30 DistributiveOmit<
31 MutationObserverResult<TData, TError, TVariables, TOnMutateResult>,
32 'mutate' | 'reset'
33 >
34β
35/**
36 * The options accepted by `useMutation`: {@link MutationOptions} as a plain object, a `ref`, or a reactive
37 * getter.
38 */
39export type UseMutationOptions<
40 TData = unknown,
41 TError = DefaultError,
42 TVariables = void,
43 TOnMutateResult = unknown,
44> =
45 | MaybeRefDeep<MutationOptions<TData, TError, TVariables, TOnMutateResult>>
46 | (() => MaybeRefDeep<
47 MutationOptions<TData, TError, TVariables, TOnMutateResult>
48 >)
49β
50type MutateSyncFunction<
51 TData = unknown,
52 TError = DefaultError,
53 TVariables = void,
54 TOnMutateResult = unknown,
55> = (
56 ...options: Parameters<
57 MutateFunction<TData, TError, TVariables, TOnMutateResult>
58 >
59) => void
60β
61/**
62 * The result of `useMutation`: the {@link MutationObserverResult} properties wrapped in `Ref`s, plus the
63 * fire-and-forget `mutate`, the awaitable `mutateAsync`, and `reset`.
64 */
65export type UseMutationReturnType<
66 TData,
67 TError,
68 TVariables,
69 TOnMutateResult,
70 TResult = MutationResult<TData, TError, TVariables, TOnMutateResult>,
71> = ToRefs<Readonly<TResult>> & {
72 mutate: MutateSyncFunction<TData, TError, TVariables, TOnMutateResult>
73 mutateAsync: MutateFunction<TData, TError, TVariables, TOnMutateResult>
74 reset: MutationObserverResult<
75 TData,
76 TError,
77 TVariables,
78 TOnMutateResult
79 >['reset']
80}
81β
82/**
83 * Unlike queries, mutations are typically used to create/update/delete data or perform server side-effects.
84 * `useMutation` is the composable for that.
85 *
86 * `options` may be a plain object, a `ref`, or a reactive getter (`() => ({ ... })`) β pass a getter
87 * if the options themselves depend on other reactive state.
88 * @param options - The {@link UseMutationOptions} to use β everything you can pass to `useMutation`.
89 * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one provided by `VueQueryPlugin`
90 * will be used.
91 * @returns `mutate`/`mutateAsync` also accept per-call `onSuccess`/`onError`/`onSettled` callbacks as a second
92 * argument, useful for triggering call-site side effects (e.g. navigation) without coupling them to the shared
93 * mutation definition. Hook-level callbacks (passed to `options`) fire for every mutation; per-call
94 * callbacks fire only for the latest call you've made.
95 * @see {@link mutationOptions} to share these options across multiple `useMutation` call sites, or to look
96 * the mutation up elsewhere via its `mutationKey` (e.g. with `useMutationState`).
97 * @example
98 * ```vue
99 * <script setup lang="ts">
100 * import { useMutation, useQueryClient } from '@tanstack/vue-query'
101 *
102 * const queryClient = useQueryClient()
103 *
104 * const addMutation = useMutation({
105 * mutationFn: addTodo,
106 * onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
107 * })
108 *
109 * function onAdd() {
110 * addMutation.mutate('Item', {
111 * onError: (error) => console.error('Failed to add item:', error),
112 * })
113 * }
114 * </script>
115 *
116 * <template>
117 * <button @click="onAdd">Add</button>
118 * </template>
119 * ```
120 * @example
121 * Rendering the mutation's own state, rather than just firing it off:
122 * ```vue
123 * <script setup lang="ts">
124 * import { useMutation, useQueryClient } from '@tanstack/vue-query'
125 *
126 * const queryClient = useQueryClient()
127 *
128 * const addMutation = useMutation({
129 * mutationFn: addTodo,
130 * onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
131 * })
132 * </script>
133 *
134 * <template>
135 * <div v-if="addMutation.isPending.value">Adding todo...</div>
136 * <div v-else>
137 * <div v-if="addMutation.isError.value">An error occurred: {{ addMutation.error.value.message }}</div>
138 * <button @click="addMutation.mutate('Item')">Add</button>
139 * </div>
140 * </template>
141 * ```
142 * @example
143 * Optimistic update via `onMutate`, rolling back on `onError`:
144 * ```vue
145 * <script setup lang="ts">
146 * import { useMutation, useQueryClient } from '@tanstack/vue-query'
147 *
148 * const queryClient = useQueryClient()
149 *
150 * const addMutation = useMutation({
151 * mutationFn: addTodo,
152 * onMutate: async (newTodo: string) => {
153 * await queryClient.cancelQueries({ queryKey: ['todos'] })
154 * const previousTodos = queryClient.getQueryData<Array<string>>(['todos'])
155 *
156 * queryClient.setQueryData<Array<string>>(['todos'], (old) => [
157 * ...(old ?? []),
158 * newTodo,
159 * ])
160 *
161 * // Passed to `onError` as `onMutateResult` if the mutation fails.
162 * return { previousTodos }
163 * },
164 * onError: (_err, _newTodo, onMutateResult) => {
165 * queryClient.setQueryData(['todos'], onMutateResult?.previousTodos)
166 * },
167 * onSettled: () => {
168 * queryClient.invalidateQueries({ queryKey: ['todos'] })
169 * },
170 * })
171 * </script>
172 *
173 * <template>
174 * <button @click="addMutation.mutate('Item')">Add</button>
175 * </template>
176 * ```
177 * @example
178 * Callbacks passed per call to `mutate` only fire for the last call β `mutateAsync` gives you a
179 * promise per call instead, so you can wait for all of them when they succeed:
180 * ```vue
181 * <script setup lang="ts">
182 * import { useMutation, useQueryClient } from '@tanstack/vue-query'
183 *
184 * const queryClient = useQueryClient()
185 *
186 * const addMutation = useMutation({
187 * mutationFn: addTodo,
188 * onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
189 * })
190 *
191 * async function handleAddAll(todos: Array<string>) {
192 * try {
193 * await Promise.all(todos.map((todo) => addMutation.mutateAsync(todo)))
194 * } catch (error) {
195 * console.error('Failed to add todos:', error)
196 * }
197 * }
198 * </script>
199 *
200 * <template>
201 * <button @click="handleAddAll(['Todo 1', 'Todo 2', 'Todo 3'])">Add all</button>
202 * </template>
203 * ```
204 * @example
205 * If some of the mutations above can fail independently of the others, and you want to know which ones
206 * did β rather than losing that information the moment the first one rejects β swap `Promise.all` for
207 * `Promise.allSettled`:
208 * ```vue
209 * <script setup lang="ts">
210 * import { useMutation, useQueryClient } from '@tanstack/vue-query'
211 *
212 * const queryClient = useQueryClient()
213 *
214 * const addMutation = useMutation({
215 * mutationFn: addTodo,
216 * onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
217 * })
218 *
219 * async function handleAddAll(todos: Array<string>) {
220 * const addResults = await Promise.allSettled(
221 * todos.map((todo) => addMutation.mutateAsync(todo)),
222 * )
223 *
224 * addResults.forEach((addResult, index) => {
225 * if (addResult.status === 'rejected') {
226 * console.error(`Failed to add "${todos[index]}":`, addResult.reason)
227 * }
228 * })
229 * }
230 * </script>
231 *
232 * <template>
233 * <button @click="handleAddAll(['Todo 1', 'Todo 2', 'Todo 3'])">Add all</button>
234 * </template>
235 * ```
236 */
237export function useMutation<
238 TData = unknown,
239 TError = DefaultError,
240 TVariables = void,
241 TOnMutateResult = unknown,
242>(
243 options: UseMutationOptions<TData, TError, TVariables, TOnMutateResult>,
244 queryClient?: QueryClient,
245): UseMutationReturnType<TData, TError, TVariables, TOnMutateResult> {
246 if (process.env.NODE_ENV === 'development') {
247 if (!getCurrentScope()) {
248 console.warn(
249 'vue-query composable like "useQuery()" should only be used inside a "setup()" function or a running effect scope. They might otherwise lead to memory leaks.',
250 )
251 }
252 }
253β
254 const client = queryClient || useQueryClient()
255 const defaultedOptions = computed(() => {
256 const resolvedOptions = typeof options === 'function' ? options() : options
257 return client.defaultMutationOptions(cloneDeepUnref(resolvedOptions))
258 })
259 const observer = new MutationObserver(client, defaultedOptions.value)
260 const state = defaultedOptions.value.shallow
261 ? shallowReactive(observer.getCurrentResult())
262 : reactive(observer.getCurrentResult())
263β
264 const unsubscribe = observer.subscribe((result) => {
265 updateState(state, result)
266 })
267β
268 const mutate = (
269 ...args: Parameters<
270 MutateFunction<TData, TError, TVariables, TOnMutateResult>
271 >
272 ) => {
273 observer.mutate(args[0] as TVariables, args[1]).catch(() => {
274 // This is intentional
275 })
276 }
277β
278 watch(defaultedOptions, () => {
279 observer.setOptions(defaultedOptions.value)
280 })
281β
282 onScopeDispose(() => {
283 unsubscribe()
284 })
285β
286 const readonlyState = defaultedOptions.value.shallow
287 ? shallowReadonly(state)
288 : readonly(state)
289β
290 const resultRefs = toRefs(readonlyState) as ToRefs<
291 Readonly<MutationResult<TData, TError, TVariables, TOnMutateResult>>
292 >
293β
294 watch(
295 () => state.error,
296 (error) => {
297 if (
298 error &&
299 shouldThrowError(defaultedOptions.value.throwOnError, [error as TError])
300 ) {
301 throw error
302 }
303 },
304 )
305β
306 return {
307 ...resultRefs,
308 mutate,
309 mutateAsync: state.mutate,
310 reset: state.reset,
311 }
312}