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