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