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

useMutation.ts

235 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 { Accessor } from 'solid-js'
7import type { QueryClient } from './QueryClient'
8import type {
9 UseMutateFunction,
10 UseMutationOptions,
11 UseMutationResult,
12} from './types'
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 * @param options - An accessor returning the {@link UseMutationOptions} to use.
18 * @param queryClient - An accessor for a custom `QueryClient`. Otherwise, the one from the nearest context
19 * will be used.
20 * @returns `mutate`/`mutateAsync` also accept per-call `onSuccess`/`onError`/`onSettled` callbacks as a second
21 * argument, useful for triggering call-site side effects (e.g. navigation) without coupling them to the shared
22 * mutation definition. Hook-level callbacks (passed to `options`) fire for every mutation; per-call callbacks
23 * fire only for the latest call you've made, and only while the component is still mounted β€” unmounting before
24 * the mutation settles removes the subscription and prevents them from firing.
25 * @example
26 * ```tsx
27 * import { useMutation, useQueryClient } from '@tanstack/solid-query'
28 *
29 * function TodoItem(props: { id: number }) {
30 * const queryClient = useQueryClient()
31 *
32 * const deleteTodoMutation = useMutation(() => ({
33 * mutationFn: deleteTodo,
34 * onSuccess: () => {
35 * queryClient.invalidateQueries({ queryKey: ['todos'] })
36 * },
37 * }))
38 *
39 * return (
40 * <button onClick={() => deleteTodoMutation.mutate({ id: props.id })} disabled={deleteTodoMutation.isPending}>
41 * Delete
42 * </button>
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 * @example
72 * Optimistic update via `onMutate`, rolling back on `onError`:
73 * ```tsx
74 * import { useMutation, useQueryClient } from '@tanstack/solid-query'
75 *
76 * function AddTodo() {
77 * const queryClient = useQueryClient()
78 *
79 * const addMutation = useMutation(() => ({
80 * mutationFn: addTodo,
81 * onMutate: async (newTodo) => {
82 * await queryClient.cancelQueries({ queryKey: ['todos'] })
83 * const previousTodos = queryClient.getQueryData<Array<string>>(['todos'])
84 *
85 * queryClient.setQueryData<Array<string>>(['todos'], (old) => [
86 * ...(old ?? []),
87 * newTodo,
88 * ])
89 *
90 * // Passed to `onError` as `onMutateResult` if the mutation fails.
91 * return { previousTodos }
92 * },
93 * onError: (_err, _newTodo, onMutateResult) => {
94 * queryClient.setQueryData(['todos'], onMutateResult?.previousTodos)
95 * },
96 * onSettled: () => {
97 * queryClient.invalidateQueries({ queryKey: ['todos'] })
98 * },
99 * }))
100 *
101 * return (
102 * <button onClick={() => addMutation.mutate('Item')}>Add</button>
103 * )
104 * }
105 * ```
106 * @example
107 * Callbacks passed per call to `mutate` only fire for the last call β€” `mutateAsync` gives you a
108 * promise per call instead, so you can wait for all of them when they succeed:
109 * ```tsx
110 * import { useMutation, useQueryClient } from '@tanstack/solid-query'
111 *
112 * function AddTodos() {
113 * const queryClient = useQueryClient()
114 *
115 * const addMutation = useMutation(() => ({
116 * mutationFn: addTodo,
117 * onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
118 * }))
119 *
120 * async function handleAddAll(todos: Array<string>) {
121 * try {
122 * await Promise.all(todos.map((todo) => addMutation.mutateAsync(todo)))
123 * } catch (error) {
124 * console.error('Failed to add todos:', error)
125 * }
126 * }
127 *
128 * return (
129 * <button onClick={() => handleAddAll(['Todo 1', 'Todo 2', 'Todo 3'])}>
130 * Add all
131 * </button>
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 */
170export function useMutation<
171 TData = unknown,
172 TError = DefaultError,
173 TVariables = void,
174 TOnMutateResult = unknown,
175>(
176 options: UseMutationOptions<TData, TError, TVariables, TOnMutateResult>,
177 queryClient?: Accessor<QueryClient>,
178): UseMutationResult<TData, TError, TVariables, TOnMutateResult> {
179 const resolveClient = useQueryClientResolver(queryClient)
180 const client = createMemo(() => resolveClient())
181​
182 const observer = new MutationObserver<
183 TData,
184 TError,
185 TVariables,
186 TOnMutateResult
187 >(client(), options())
188​
189 const mutate: UseMutateFunction<
190 TData,
191 TError,
192 TVariables,
193 TOnMutateResult
194 > = (...args) => {
195 observer.mutate(args[0] as TVariables, args[1]).catch(noop)
196 }
197​
198 const [state, setState] = createStore<
199 UseMutationResult<TData, TError, TVariables, TOnMutateResult>
200 >({
201 ...observer.getCurrentResult(),
202 mutate,
203 mutateAsync: observer.getCurrentResult().mutate,
204 })
205​
206 createComputed(() => {
207 observer.setOptions(options())
208 })
209​
210 createComputed(
211 on(
212 () => state.status,
213 () => {
214 if (
215 state.isError &&
216 shouldThrowError(observer.options.throwOnError, [state.error])
217 ) {
218 throw state.error
219 }
220 },
221 ),
222 )
223​
224 const unsubscribe = observer.subscribe((result) => {
225 setState({
226 ...result,
227 mutate,
228 mutateAsync: result.mutate,
229 })
230 })
231​
232 onCleanup(unsubscribe)
233​
234 return state