Open History to see the last commit
1import {
2 MutationObserver,
3 noop,
4 notifyManager,
5 shouldThrowError,
6} from '@tanstack/query-core'
7import type { DefaultError, QueryClient } from '@tanstack/query-core'
8import { useCallback, useEffect, useState } from 'preact/hooks'
9β
10import { useQueryClient } from './QueryClientProvider'
11import type {
12 UseMutateFunction,
13 UseMutationOptions,
14 UseMutationResult,
15} from './types'
16import { useSyncExternalStore } from './utils'
17β
18// HOOK
19β
20/**
21 * Unlike queries, mutations are typically used to create/update/delete data or perform server side-effects.
22 * `useMutation` is the hook for that.
23 *
24 * @see {@link mutationOptions} to share these options across multiple `useMutation` call sites, or to look
25 * the mutation up elsewhere via its `mutationKey` (e.g. with `useMutationState`).
26 * @param options - The {@link UseMutationOptions} to use β everything you can pass to `useMutation`.
27 * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
28 * be used.
29 * @returns `mutate`/`mutateAsync` also accept per-call `onSuccess`/`onError`/`onSettled` callbacks as a second
30 * argument, useful for triggering call-site side effects (e.g. navigation) without coupling them to the shared
31 * mutation definition. If you make multiple requests, `onSuccess` will fire only after the latest call you've
32 * made.
33 *
34 * @example
35 * ```tsx
36 * import { useMutation, useQueryClient } from '@tanstack/preact-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/preact-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/preact-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 `context` if the mutation fails.
110 * return { previousTodos }
111 * },
112 * onError: (_err, _newTodo, context) => {
113 * queryClient.setQueryData(['todos'], context?.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/preact-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/preact-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] = useState(
203 () =>
204 new MutationObserver<TData, TError, TVariables, TOnMutateResult>(
205 client,
206 options,
207 ),
208 )
209β
210 useEffect(() => {
211 observer.setOptions(options)
212 }, [observer, options])
213β
214 const result = useSyncExternalStore(
215 useCallback(
216 (onStoreChange) =>
217 observer.subscribe(notifyManager.batchCalls(onStoreChange)),
218 [observer],
219 ),
220 () => observer.getCurrentResult(),
221 )
222β
223 const mutate = useCallback<
224 UseMutateFunction<TData, TError, TVariables, TOnMutateResult>
225 >(
226 (
227 ...args: Parameters<
228 UseMutateFunction<TData, TError, TVariables, TOnMutateResult>
229 >
230 ) => {
231 observer.mutate(args[0] as TVariables, args[1]).catch(noop)
232 },
233 [observer],
234 )
235β
236 if (
237 result.error &&
238 shouldThrowError(observer.options.throwOnError, [result.error])
239 ) {
240 throw result.error
241 }
242β
243 return { ...result, mutate, mutateAsync: result.mutate }
244}