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