Open History to see the last commit
1import { MutationObserver, noop, shouldThrowError } from '@tanstack/query-core'
2import {
3 createComputed,
4 createMemo,
5 createSignal,
6 on,
7 onCleanup,
8} from 'solid-js'
9import { createStore } from 'solid-js/store'
10import { useQueryClientResolver } from './QueryClientProvider'
11import type { DefaultError } from '@tanstack/query-core'
12import type { QueryClient } from './QueryClient'
13import type {
14 UseMutateFunction,
15 UseMutationOptions,
16 UseMutationResult,
17} from './types'
18import type { Accessor } from 'solid-js'
19β
20/**
21 * Unlike queries, mutations are typically used to create/update/delete data or perform server side-effects.
22 * `useMutation` is the primitive for that.
23 * @param options - An accessor returning the {@link UseMutationOptions} to use.
24 * @param queryClient - An accessor for a custom `QueryClient`. Otherwise, the one from the nearest context
25 * will 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 * @example
32 * ```tsx
33 * import { useMutation, useQueryClient } from '@tanstack/solid-query'
34 *
35 * function TodoItem(props: { id: number }) {
36 * const queryClient = useQueryClient()
37 *
38 * const deleteTodoMutation = useMutation(() => ({
39 * mutationFn: deleteTodo,
40 * onSuccess: () => {
41 * queryClient.invalidateQueries({ queryKey: ['todos'] })
42 * },
43 * }))
44 *
45 * return (
46 * <button onClick={() => deleteTodoMutation.mutate({ id: props.id })} disabled={deleteTodoMutation.isPending}>
47 * Delete
48 * </button>
49 * )
50 * }
51 * ```
52 * @example
53 * Rendering the mutation's own state, rather than just firing it off:
54 * ```tsx
55 * import { Match, Switch } from 'solid-js'
56 * import { useMutation, useQueryClient } from '@tanstack/solid-query'
57 *
58 * function AddTodo() {
59 * const queryClient = useQueryClient()
60 *
61 * const addMutation = useMutation(() => ({
62 * mutationFn: addTodo,
63 * onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
64 * }))
65 *
66 * return (
67 * <Switch fallback={<button onClick={() => addMutation.mutate('Item')}>Add</button>}>
68 * <Match when={addMutation.isPending}>Adding todo...</Match>
69 * <Match when={addMutation.isError}>
70 * <div>An error occurred: {addMutation.error?.message}</div>
71 * <button onClick={() => addMutation.mutate('Item')}>Add</button>
72 * </Match>
73 * </Switch>
74 * )
75 * }
76 * ```
77 * @example
78 * Optimistic update via `onMutate`, rolling back on `onError`:
79 * ```tsx
80 * import { useMutation, useQueryClient } from '@tanstack/solid-query'
81 *
82 * function AddTodo() {
83 * const queryClient = useQueryClient()
84 *
85 * const addMutation = useMutation(() => ({
86 * mutationFn: addTodo,
87 * onMutate: async (newTodo) => {
88 * await queryClient.cancelQueries({ queryKey: ['todos'] })
89 * const previousTodos = queryClient.getQueryData<Array<string>>(['todos'])
90 *
91 * queryClient.setQueryData<Array<string>>(['todos'], (old) => [
92 * ...(old ?? []),
93 * newTodo,
94 * ])
95 *
96 * // Passed to `onError` as `onMutateResult` if the mutation fails.
97 * return { previousTodos }
98 * },
99 * onError: (_err, _newTodo, onMutateResult) => {
100 * queryClient.setQueryData(['todos'], onMutateResult?.previousTodos)
101 * },
102 * onSettled: () => {
103 * queryClient.invalidateQueries({ queryKey: ['todos'] })
104 * },
105 * }))
106 *
107 * return (
108 * <button onClick={() => addMutation.mutate('Item')}>Add</button>
109 * )
110 * }
111 * ```
112 * @example
113 * Callbacks passed per call to `mutate` only fire for the last call β `mutateAsync` gives you a
114 * promise per call instead, so you can wait for all of them when they succeed:
115 * ```tsx
116 * import { useMutation, useQueryClient } from '@tanstack/solid-query'
117 *
118 * function AddTodos() {
119 * const queryClient = useQueryClient()
120 *
121 * const addMutation = useMutation(() => ({
122 * mutationFn: addTodo,
123 * onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
124 * }))
125 *
126 * async function handleAddAll(todos: Array<string>) {
127 * try {
128 * await Promise.all(todos.map((todo) => addMutation.mutateAsync(todo)))
129 * } catch (error) {
130 * console.error('Failed to add todos:', error)
131 * }
132 * }
133 *
134 * return (
135 * <button onClick={() => handleAddAll(['Todo 1', 'Todo 2', 'Todo 3'])}>
136 * Add all
137 * </button>
138 * )
139 * }
140 * ```
141 * @example
142 * If some of the mutations above can fail independently of the others, and you want to know which ones
143 * did β rather than losing that information the moment the first one rejects β swap `Promise.all` for
144 * `Promise.allSettled`:
145 * ```tsx
146 * import { useMutation, useQueryClient } from '@tanstack/solid-query'
147 *
148 * function AddTodos() {
149 * const queryClient = useQueryClient()
150 *
151 * const addMutation = useMutation(() => ({
152 * mutationFn: addTodo,
153 * onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
154 * }))
155 *
156 * async function handleAddAll(todos: Array<string>) {
157 * const addResults = await Promise.allSettled(
158 * todos.map((todo) => addMutation.mutateAsync(todo)),
159 * )
160 *
161 * addResults.forEach((addResult, index) => {
162 * if (addResult.status === 'rejected') {
163 * console.error(`Failed to add "${todos[index]}":`, addResult.reason)
164 * }
165 * })
166 * }
167 *
168 * return (
169 * <button onClick={() => handleAddAll(['Todo 1', 'Todo 2', 'Todo 3'])}>
170 * Add all
171 * </button>
172 * )
173 * }
174 * ```
175 */
176export function useMutation<
177 TData = unknown,
178 TError = DefaultError,
179 TVariables = void,
180 TOnMutateResult = unknown,
181>(
182 options: UseMutationOptions<TData, TError, TVariables, TOnMutateResult>,
183 queryClient?: Accessor<QueryClient>,
184): UseMutationResult<TData, TError, TVariables, TOnMutateResult> {
185 const resolveClient = useQueryClientResolver(queryClient)
186 const client = createMemo(() => resolveClient())
187β
188 const [observer, setObserver] = createSignal(
189 new MutationObserver<TData, TError, TVariables, TOnMutateResult>(
190 client(),
191 options(),
192 ),
193 )
194β
195 const mutate: UseMutateFunction<
196 TData,
197 TError,
198 TVariables,
199 TOnMutateResult
200 > = (...args) => {
201 observer()
202 .mutate(args[0] as TVariables, args[1])
203 .catch(noop)
204 }
205β
206 const [state, setState] = createStore<
207 UseMutationResult<TData, TError, TVariables, TOnMutateResult>
208 >({
209 ...observer().getCurrentResult(),
210 mutate,
211 mutateAsync: observer().getCurrentResult().mutate,
212 })
213β
214 createComputed(() => {
215 observer().setOptions(options())
216 })
217β
218 createComputed(
219 on(
220 () => state.status,
221 () => {
222 if (
223 state.isError &&
224 shouldThrowError(observer().options.throwOnError, [state.error])
225 ) {
226 throw state.error
227 }
228 },
229 ),
230 )
231β
232 const subscribeToObserver = () =>
233 observer().subscribe((result) => {
234 setState({
235 ...result,
236 mutate,
237 mutateAsync: result.mutate,
238 })
239 })
240β
241 let unsubscribe = subscribeToObserver()
242β
243 createComputed(
244 on(
245 client,
246 (c) => {
247 unsubscribe()
248 const newObserver = new MutationObserver<
249 TData,
250 TError,
251 TVariables,
252 TOnMutateResult
253 >(c, options())
254 setObserver(newObserver)
255 setState({
256 ...newObserver.getCurrentResult(),
257 mutate,
258 mutateAsync: newObserver.getCurrentResult().mutate,
259 })
260 unsubscribe = subscribeToObserver()
261 },
262 { defer: true },
263 ),
264 )
265β
266 onCleanup(() => unsubscribe())
267β
268 return state
269}