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

useMutation.ts

247 lines7.2 KB

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