Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

useMutation.ts

252 lines7.2 KB

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