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. Hook-level callbacks (passed to `options`) fire for every mutation; per-call callbacks
32 * fire only for the latest call you've made, and only while the component is still mounted β unmounting before
33 * the mutation settles removes the subscription and prevents them from firing.
34 *
35 * @example
36 * ```tsx
37 * import { useMutation, useQueryClient } from '@tanstack/preact-query'
38 *
39 * function AddTodo() {
40 * const queryClient = useQueryClient()
41 *
42 * const addMutation = useMutation({
43 * mutationFn: addTodo,
44 * onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
45 * })
46 *
47 * return (
48 * <button
49 * onClick={() =>
50 * addMutation.mutate('Item', {
51 * onError: (error) => console.error('Failed to add item:', error),
52 * })
53 * }
54 * >
55 * Add
56 * </button>
57 * )
58 * }
59 * ```
60 *
61 * @example
62 * Rendering the mutation's own state, rather than just firing it off:
63 * ```tsx
64 * import { useMutation, useQueryClient } from '@tanstack/preact-query'
65 *
66 * function AddTodo() {
67 * const queryClient = useQueryClient()
68 *
69 * const addMutation = useMutation({
70 * mutationFn: addTodo,
71 * onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
72 * })
73 *
74 * return (
75 * <div>
76 * {addMutation.isPending ? (
77 * 'Adding todo...'
78 * ) : (
79 * <>
80 * {addMutation.isError ? (
81 * <div>An error occurred: {addMutation.error.message}</div>
82 * ) : null}
83 * <button onClick={() => addMutation.mutate('Item')}>Add</button>
84 * </>
85 * )}
86 * </div>
87 * )
88 * }
89 * ```
90 *
91 * @example
92 * Optimistic update via `onMutate`, rolling back on `onError`:
93 * ```tsx
94 * import { useMutation, useQueryClient } from '@tanstack/preact-query'
95 *
96 * function AddTodo() {
97 * const queryClient = useQueryClient()
98 *
99 * const addMutation = useMutation({
100 * mutationFn: addTodo,
101 * onMutate: async (newTodo) => {
102 * await queryClient.cancelQueries({ queryKey: ['todos'] })
103 * const previousTodos = queryClient.getQueryData<Array<string>>(['todos'])
104 *
105 * queryClient.setQueryData<Array<string>>(['todos'], (old) => [
106 * ...(old ?? []),
107 * newTodo,
108 * ])
109 *
110 * // Passed to `onError` as `onMutateResult` if the mutation fails.
111 * return { previousTodos }
112 * },
113 * onError: (_err, _newTodo, onMutateResult) => {
114 * queryClient.setQueryData(['todos'], onMutateResult?.previousTodos)
115 * },
116 * onSettled: () => {
117 * queryClient.invalidateQueries({ queryKey: ['todos'] })
118 * },
119 * })
120 *
121 * return (
122 * <button onClick={() => addMutation.mutate('Item')}>Add</button>
123 * )
124 * }
125 * ```
126 *
127 * @example
128 * Callbacks passed per call to `mutate` only fire for the last call β `mutateAsync` gives you a
129 * promise per call instead, so you can wait for all of them:
130 * ```tsx
131 * import { useMutation, useQueryClient } from '@tanstack/preact-query'
132 *
133 * function AddTodos() {
134 * const queryClient = useQueryClient()
135 *
136 * const addMutation = useMutation({
137 * mutationFn: addTodo,
138 * onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
139 * })
140 *
141 * async function handleAddAll(todos: Array<string>) {
142 * try {
143 * await Promise.all(todos.map((todo) => addMutation.mutateAsync(todo)))
144 * } catch (error) {
145 * console.error('Failed to add todos:', error)
146 * }
147 * }
148 *
149 * return (
150 * <button onClick={() => handleAddAll(['Todo 1', 'Todo 2', 'Todo 3'])}>
151 * Add all
152 * </button>
153 * )
154 * }
155 * ```
156 *
157 * @example
158 * If some of the mutations above can fail independently of the others, and you want to know which ones
159 * did β rather than losing that information the moment the first one rejects β swap `Promise.all` for
160 * `Promise.allSettled`:
161 * ```tsx
162 * import { useMutation, useQueryClient } from '@tanstack/preact-query'
163 *
164 * function AddTodos() {
165 * const queryClient = useQueryClient()
166 *
167 * const addMutation = useMutation({
168 * mutationFn: addTodo,
169 * onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
170 * })
171 *
172 * async function handleAddAll(todos: Array<string>) {
173 * const addResults = await Promise.allSettled(
174 * todos.map((todo) => addMutation.mutateAsync(todo)),
175 * )
176 *
177 * addResults.forEach((addResult, index) => {
178 * if (addResult.status === 'rejected') {
179 * console.error(`Failed to add "${todos[index]}":`, addResult.reason)
180 * }
181 * })
182 * }
183 *
184 * return (
185 * <button onClick={() => handleAddAll(['Todo 1', 'Todo 2', 'Todo 3'])}>
186 * Add all
187 * </button>
188 * )
189 * }
190 * ```
191 */
192export function useMutation<
193 TData = unknown,
194 TError = DefaultError,
195 TVariables = void,
196 TOnMutateResult = unknown,
197>(
198 options: UseMutationOptions<TData, TError, TVariables, TOnMutateResult>,
199 queryClient?: QueryClient,
200): UseMutationResult<TData, TError, TVariables, TOnMutateResult> {
201 const client = useQueryClient(queryClient)
202β
203 const [observer] = useState(
204 () =>
205 new MutationObserver<TData, TError, TVariables, TOnMutateResult>(
206 client,
207 options,
208 ),
209 )
210β
211 useEffect(() => {
212 observer.setOptions(options)
213 }, [observer, options])
214β
215 const result = useSyncExternalStore(
216 useCallback(
217 (onStoreChange) =>
218 observer.subscribe(notifyManager.batchCalls(onStoreChange)),
219 [observer],
220 ),
221 () => observer.getCurrentResult(),
222 )
223β
224 const mutate = 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}