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

useMutation.ts

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