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