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

createMutation.md

202 lines5.8 KB

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 )
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 )
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 )
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 )
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 )
202```