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

createMutation.md

204 lines5.8 KB

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