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

useMutation.ts

241 lines7.3 KB

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