Open History to see the last commit
1'use client'
2import {
3 MutationObserver,
4 noop,
5 notifyManager,
6 shouldThrowError,
7} from '@tanstack/query-core'
8import * as React from 'react'
9import { useQueryClient } from './QueryClientProvider'
10import type { DefaultError, QueryClient } from '@tanstack/query-core'
11import type {
12 UseMutateFunction,
13 UseMutationOptions,
14 UseMutationResult,
15} from './types'
16β
17// HOOK
18β
19/**
20 * Unlike queries, mutations are typically used to create/update/delete data or perform server side-effects.
21 * `useMutation` is the hook for that.
22 * @param options - The {@link UseMutationOptions} to use β everything you can pass to `useMutation`.
23 * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
24 * be used.
25 * @returns `mutate`/`mutateAsync` also accept per-call `onSuccess`/`onError`/`onSettled` callbacks as a second
26 * argument, useful for triggering call-site side effects (e.g. navigation) without coupling them to the shared
27 * mutation definition. Hook-level callbacks (passed to `options`) fire for every mutation; per-call callbacks
28 * fire only for the latest call you've made, and only while the component is still mounted β unmounting before
29 * the mutation settles removes the subscription and prevents them from firing.
30 * @throws {Error} The mutation error, when `throwOnError` is `true` or returns `true` for it, so that it is
31 * thrown to the nearest error boundary.
32 * @see {@link mutationOptions} to share these options across multiple `useMutation` call sites, or to look
33 * the mutation up elsewhere via its `mutationKey` (e.g. with `useMutationState`).
34 * @example
35 * ```tsx
36 * import { useMutation, useQueryClient } from '@tanstack/react-query'
37 *
38 * function AddTodo() {
39 * const queryClient = useQueryClient()
40 *
41 * const addMutation = useMutation({
42 * mutationFn: addTodo,
43 * onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
44 * })
45 *
46 * return (
47 * <button
48 * onClick={() =>
49 * addMutation.mutate('Item', {
50 * onError: (error) => console.error('Failed to add item:', error),
51 * })
52 * }
53 * >
54 * Add
55 * </button>
56 * )
57 * }
58 * ```
59 * @example
60 * Rendering the mutation's own state, rather than just firing it off:
61 * ```tsx
62 * import { useMutation, useQueryClient } from '@tanstack/react-query'
63 *
64 * function AddTodo() {
65 * const queryClient = useQueryClient()
66 *
67 * const addMutation = useMutation({
68 * mutationFn: addTodo,
69 * onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
70 * })
71 *
72 * return (
73 * <div>
74 * {addMutation.isPending ? (
75 * 'Adding todo...'
76 * ) : (
77 * <>
78 * {addMutation.isError ? (
79 * <div>An error occurred: {addMutation.error.message}</div>
80 * ) : null}
81 * <button onClick={() => addMutation.mutate('Item')}>Add</button>
82 * </>
83 * )}
84 * </div>
85 * )
86 * }
87 * ```
88 * @example
89 * Optimistic update via `onMutate`, rolling back on `onError`:
90 * ```tsx
91 * import { useMutation, useQueryClient } from '@tanstack/react-query'
92 *
93 * function AddTodo() {
94 * const queryClient = useQueryClient()
95 *
96 * const addMutation = useMutation({
97 * mutationFn: addTodo,
98 * onMutate: async (newTodo) => {
99 * await queryClient.cancelQueries({ queryKey: ['todos'] })
100 * const previousTodos = queryClient.getQueryData<Array<string>>(['todos'])
101 *
102 * queryClient.setQueryData<Array<string>>(['todos'], (old) => [
103 * ...(old ?? []),
104 * newTodo,
105 * ])
106 *
107 * // Passed to `onError` as `onMutateResult` if the mutation fails.
108 * return { previousTodos }
109 * },
110 * onError: (_err, _newTodo, onMutateResult) => {
111 * queryClient.setQueryData(['todos'], onMutateResult?.previousTodos)
112 * },
113 * onSettled: () => {
114 * queryClient.invalidateQueries({ queryKey: ['todos'] })
115 * },
116 * })
117 *
118 * return (
119 * <button onClick={() => addMutation.mutate('Item')}>Add</button>
120 * )
121 * }
122 * ```
123 * @example
124 * Callbacks passed per call to `mutate` only fire for the last call β `mutateAsync` gives you a
125 * promise per call instead, so you can wait for all of them when they succeed:
126 * ```tsx
127 * import { useMutation, useQueryClient } from '@tanstack/react-query'
128 *
129 * function AddTodos() {
130 * const queryClient = useQueryClient()
131 *
132 * const addMutation = useMutation({
133 * mutationFn: addTodo,
134 * onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
135 * })
136 *
137 * async function handleAddAll(todos: Array<string>) {
138 * try {
139 * await Promise.all(todos.map((todo) => addMutation.mutateAsync(todo)))
140 * } catch (error) {
141 * console.error('Failed to add todos:', error)
142 * }
143 * }
144 *
145 * return (
146 * <button onClick={() => handleAddAll(['Todo 1', 'Todo 2', 'Todo 3'])}>
147 * Add all
148 * </button>
149 * )
150 * }
151 * ```
152 * @example
153 * If some of the mutations above can fail independently of the others, and you want to know which ones
154 * did β rather than losing that information the moment the first one rejects β swap `Promise.all` for
155 * `Promise.allSettled`:
156 * ```tsx
157 * import { useMutation, useQueryClient } from '@tanstack/react-query'
158 *
159 * function AddTodos() {
160 * const queryClient = useQueryClient()
161 *
162 * const addMutation = useMutation({
163 * mutationFn: addTodo,
164 * onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
165 * })
166 *
167 * async function handleAddAll(todos: Array<string>) {
168 * const addResults = await Promise.allSettled(
169 * todos.map((todo) => addMutation.mutateAsync(todo)),
170 * )
171 *
172 * addResults.forEach((addResult, index) => {
173 * if (addResult.status === 'rejected') {
174 * console.error(`Failed to add "${todos[index]}":`, addResult.reason)
175 * }
176 * })
177 * }
178 *
179 * return (
180 * <button onClick={() => handleAddAll(['Todo 1', 'Todo 2', 'Todo 3'])}>
181 * Add all
182 * </button>
183 * )
184 * }
185 * ```
186 */
187export function useMutation<
188 TData = unknown,
189 TError = DefaultError,
190 TVariables = void,
191 TOnMutateResult = unknown,
192>(
193 options: UseMutationOptions<TData, TError, TVariables, TOnMutateResult>,
194 queryClient?: QueryClient,
195): UseMutationResult<TData, TError, TVariables, TOnMutateResult> {
196 const client = useQueryClient(queryClient)
197β
198 const [observer] = React.useState(
199 () =>
200 new MutationObserver<TData, TError, TVariables, TOnMutateResult>(
201 client,
202 options,
203 ),
204 )
205β
206 React.useEffect(() => {
207 observer.setOptions(options)
208 }, [observer, options])
209β
210 const result = React.useSyncExternalStore(
211 React.useCallback(
212 (onStoreChange) =>
213 observer.subscribe(notifyManager.batchCalls(onStoreChange)),
214 [observer],
215 ),
216 () => observer.getCurrentResult(),
217 () => observer.getCurrentResult(),
218 )
219β
220 const mutate = React.useCallback<
221 UseMutateFunction<TData, TError, TVariables, TOnMutateResult>
222 >(
223 (
224 ...args: Parameters<
225 UseMutateFunction<TData, TError, TVariables, TOnMutateResult>
226 >
227 ) => {
228 observer.mutate(args[0] as TVariables, args[1]).catch(noop)
229 },
230 [observer],
231 )
232β
233 if (
234 result.error &&
235 shouldThrowError(observer.options.throwOnError, [result.error])
236 ) {
237 throw result.error
238 }
239β
240 return { ...result, mutate, mutateAsync: result.mutate }
241}