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

useMutation.md

218 lines6.3 KB

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