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

useMutation.ts

241 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 perform server side-effects.
16 * `useMutation` is the primitive for that.
17 *
18 * @param options - An accessor returning the {@link UseMutationOptions} to use.
19 * @param queryClient - An accessor for a custom `QueryClient`. Otherwise, the one from the nearest context
20 * will be used.
21 * @returns `mutate`/`mutateAsync` also accept per-call `onSuccess`/`onError`/`onSettled` callbacks as a second
22 * argument, useful for triggering call-site side effects (e.g. navigation) without coupling them to the shared
23 * mutation definition. Hook-level callbacks (passed to `options`) fire for every mutation; per-call callbacks
24 * fire only for the latest call you've made, and only while the component is still mounted β€” unmounting before
25 * the mutation settles removes the subscription and prevents them from firing.
26 *
27 * @example
28 * ```tsx
29 * import { useMutation, useQueryClient } from '@tanstack/solid-query'
30 *
31 * function TodoItem(props: { id: number }) {
32 * const queryClient = useQueryClient()
33 *
34 * const deleteTodoMutation = useMutation(() => ({
35 * mutationFn: deleteTodo,
36 * onSuccess: () => {
37 * queryClient.invalidateQueries({ queryKey: ['todos'] })
38 * },
39 * }))
40 *
41 * return (
42 * <button onClick={() => deleteTodoMutation.mutate({ id: props.id })} disabled={deleteTodoMutation.isPending}>
43 * Delete
44 * </button>
45 * )
46 * }
47 * ```
48 *
49 * @example
50 * Rendering the mutation's own state, rather than just firing it off:
51 * ```tsx
52 * import { Match, Switch } from 'solid-js'
53 * import { useMutation, useQueryClient } from '@tanstack/solid-query'
54 *
55 * function AddTodo() {
56 * const queryClient = useQueryClient()
57 *
58 * const addMutation = useMutation(() => ({
59 * mutationFn: addTodo,
60 * onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
61 * }))
62 *
63 * return (
64 * <Switch fallback={<button onClick={() => addMutation.mutate('Item')}>Add</button>}>
65 * <Match when={addMutation.isPending}>Adding todo...</Match>
66 * <Match when={addMutation.isError}>
67 * <div>An error occurred: {addMutation.error?.message}</div>
68 * <button onClick={() => addMutation.mutate('Item')}>Add</button>
69 * </Match>
70 * </Switch>
71 * )
72 * }
73 * ```
74 *
75 * @example
76 * Optimistic update via `onMutate`, rolling back on `onError`:
77 * ```tsx
78 * import { useMutation, useQueryClient } from '@tanstack/solid-query'
79 *
80 * function AddTodo() {
81 * const queryClient = useQueryClient()
82 *
83 * const addMutation = useMutation(() => ({
84 * mutationFn: addTodo,
85 * onMutate: async (newTodo) => {
86 * await queryClient.cancelQueries({ queryKey: ['todos'] })
87 * const previousTodos = queryClient.getQueryData<Array<string>>(['todos'])
88 *
89 * queryClient.setQueryData<Array<string>>(['todos'], (old) => [
90 * ...(old ?? []),
91 * newTodo,
92 * ])
93 *
94 * // Passed to `onError` as `onMutateResult` if the mutation fails.
95 * return { previousTodos }
96 * },
97 * onError: (_err, _newTodo, onMutateResult) => {
98 * queryClient.setQueryData(['todos'], onMutateResult?.previousTodos)
99 * },
100 * onSettled: () => {
101 * queryClient.invalidateQueries({ queryKey: ['todos'] })
102 * },
103 * }))
104 *
105 * return (
106 * <button onClick={() => addMutation.mutate('Item')}>Add</button>
107 * )
108 * }
109 * ```
110 *
111 * @example
112 * Callbacks passed per call to `mutate` only fire for the last call β€” `mutateAsync` gives you a
113 * promise per call instead, so you can wait for all of them when they succeed:
114 * ```tsx
115 * import { useMutation, useQueryClient } from '@tanstack/solid-query'
116 *
117 * function AddTodos() {
118 * const queryClient = useQueryClient()
119 *
120 * const addMutation = useMutation(() => ({
121 * mutationFn: addTodo,
122 * onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
123 * }))
124 *
125 * async function handleAddAll(todos: Array<string>) {
126 * try {
127 * await Promise.all(todos.map((todo) => addMutation.mutateAsync(todo)))
128 * } catch (error) {
129 * console.error('Failed to add todos:', error)
130 * }
131 * }
132 *
133 * return (
134 * <button onClick={() => handleAddAll(['Todo 1', 'Todo 2', 'Todo 3'])}>
135 * Add all
136 * </button>
137 * )
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 = new MutationObserver<
189 TData,
190 TError,
191 TVariables,
192 TOnMutateResult
193 >(client(), options())
194​
195 const mutate: UseMutateFunction<
196 TData,
197 TError,
198 TVariables,
199 TOnMutateResult
200 > = (...args) => {
201 observer.mutate(args[0] as TVariables, args[1]).catch(noop)
202 }
203​
204 const [state, setState] = createStore<
205 UseMutationResult<TData, TError, TVariables, TOnMutateResult>
206 >({
207 ...observer.getCurrentResult(),
208 mutate,
209 mutateAsync: observer.getCurrentResult().mutate,
210 })
211​
212 createComputed(() => {
213 observer.setOptions(options())
214 })
215​
216 createComputed(
217 on(
218 () => state.status,
219 () => {
220 if (
221 state.isError &&
222 shouldThrowError(observer.options.throwOnError, [state.error])
223 ) {
224 throw state.error
225 }
226 },
227 ),
228 )
229​
230 const unsubscribe = observer.subscribe((result) => {
231 setState({
232 ...result,
233 mutate,
234 mutateAsync: result.mutate,
235 })
236 })
237​
238 onCleanup(unsubscribe)
239​
240 return state