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

useMutation.md

216 lines6.2 KB

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