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