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