Open History to see the last commit
1---
2id: useMutation
3title: useMutation
4---
5β
6```tsx
7const {
8 data,
9 error,
10 isError,
11 isIdle,
12 isPending,
13 isPaused,
14 isSuccess,
15 failureCount,
16 failureReason,
17 mutate,
18 mutateAsync,
19 reset,
20 status,
21 submittedAt,
22 variables,
23} = useMutation({
24 mutationFn,
25 gcTime,
26 meta,
27 mutationKey,
28 networkMode,
29 onError,
30 onMutate,
31 onSettled,
32 onSuccess,
33 retry,
34 retryDelay,
35 scope,
36 throwOnError,
37})
38β
39mutate(variables, {
40 onError,
41 onSettled,
42 onSuccess,
43})
44```
45β
46**Options**
47β
48- `mutationFn: (variables: TVariables) => Promise<TData>`
49 - **Required, but only if no default mutation function has been defined**
50 - A function that performs an asynchronous task and returns a promise.
51 - `variables` is an object that `mutate` will pass to your `mutationFn`
52- `gcTime: number | Infinity`
53 - The time in milliseconds that unused/inactive cache data remains in memory. When a mutation's cache becomes unused or inactive, that cache data will be garbage collected after this duration. When different cache times are specified, the longest one will be used.
54 - If set to `Infinity`, will disable garbage collection
55 - Note: the maximum allowed time is about 24 days. See [more](https://developer.mozilla.org/en-US/docs/Web/API/setTimeout#maximum_delay_value).
56- `mutationKey: unknown[]`
57 - Optional
58 - A mutation key can be set to inherit defaults set with `queryClient.setMutationDefaults`.
59- `networkMode: 'online' | 'always' | 'offlineFirst`
60 - Optional
61 - defaults to `'online'`
62 - see [Network Mode](../../guides/network-mode) for more information.
63- `onMutate: (variables: TVariables) => Promise<TContext | void> | TContext | void`
64 - Optional
65 - This function will fire before the mutation function is fired and is passed the same variables the mutation function would receive
66 - Useful to perform optimistic updates to a resource in hopes that the mutation succeeds
67 - The value returned from this function will be passed to both the `onError` and `onSettled` functions in the event of a mutation failure and can be useful for rolling back optimistic updates.
68- `onSuccess: (data: TData, variables: TVariables, context: TContext) => Promise<unknown> | unknown`
69 - Optional
70 - This function will fire when the mutation is successful and will be passed the mutation's result.
71 - If a promise is returned, it will be awaited and resolved before proceeding
72- `onError: (err: TError, variables: TVariables, context?: TContext) => Promise<unknown> | unknown`
73 - Optional
74 - This function will fire if the mutation encounters an error and will be passed the error.
75 - If a promise is returned, it will be awaited and resolved before proceeding
76- `onSettled: (data: TData, error: TError, variables: TVariables, context?: TContext) => Promise<unknown> | unknown`
77 - Optional
78 - This function will fire when the mutation is either successfully fetched or encounters an error and be passed either the data or error
79 - If a promise is returned, it will be awaited and resolved before proceeding
80- `retry: boolean | number | (failureCount: number, error: TError) => boolean`
81 - Defaults to `0`.
82 - If `false`, failed mutations will not retry.
83 - If `true`, failed mutations will retry infinitely.
84 - If set to an `number`, e.g. `3`, failed mutations will retry until the failed mutations count meets that number.
85- `retryDelay: number | (retryAttempt: number, error: TError) => number`
86 - This function receives a `retryAttempt` integer and the actual Error and returns the delay to apply before the next attempt in milliseconds.
87 - A function like `attempt => Math.min(attempt > 1 ? 2 ** attempt * 1000 : 1000, 30 * 1000)` applies exponential backoff.
88 - A function like `attempt => attempt * 1000` applies linear backoff.
89- `scope: { id: string }`
90 - Optional
91 - Defaults to a unique id (so that all mutations run in parallel)
92 - Mutations with the same scope id will run in serial
93- `throwOnError: undefined | boolean | (error: TError) => boolean`
94 - Defaults to the global query config's `throwOnError` value, which is `undefined`
95 - Set this to `true` if you want mutation errors to be thrown in the render phase and propagate to the nearest error boundary
96 - Set this to `false` to disable the behavior of throwing errors to the error boundary.
97 - If set to a function, it will be passed the error and should return a boolean indicating whether to show the error in an error boundary (`true`) or return the error as state (`false`)
98- `meta: Record<string, unknown>`
99 - Optional
100 - If set, stores additional information on the mutation cache entry that can be used as needed. It will be accessible wherever the `mutation` is available (eg. `onError`, `onSuccess` functions of the `MutationCache`).
101- `queryClient?: QueryClient`,
102 - Use this to use a custom QueryClient. Otherwise, the one from the nearest context will be used.
103β
104**Returns**
105β
106- `mutate: (variables: TVariables, { onSuccess, onSettled, onError }) => void`
107 - The mutation function you can call with variables to trigger the mutation and optionally hooks on additional callback options.
108 - `variables: TVariables`
109 - Optional
110 - The variables object to pass to the `mutationFn`.
111 - `onSuccess: (data: TData, variables: TVariables, context: TContext) => void`
112 - Optional
113 - This function will fire when the mutation is successful and will be passed the mutation's result.
114 - Void function, the returned value will be ignored
115 - `onError: (err: TError, variables: TVariables, context: TContext | undefined) => void`
116 - Optional
117 - This function will fire if the mutation encounters an error and will be passed the error.
118 - Void function, the returned value will be ignored
119 - `onSettled: (data: TData | undefined, error: TError | null, variables: TVariables, context: TContext | undefined) => void`
120 - Optional
121 - This function will fire when the mutation is either successfully fetched or encounters an error and be passed either the data or error
122 - Void function, the returned value will be ignored
123 - If you make multiple requests, `onSuccess` will fire only after the latest call you've made.
124- `mutateAsync: (variables: TVariables, { onSuccess, onSettled, onError }) => Promise<TData>`
125 - Similar to `mutate` but returns a promise which can be awaited.
126- `status: string`
127 - Will be:
128 - `idle` initial status prior to the mutation function executing.
129 - `pending` if the mutation is currently executing.
130 - `error` if the last mutation attempt resulted in an error.
131 - `success` if the last mutation attempt was successful.
132- `isIdle`, `isPending`, `isSuccess`, `isError`: boolean variables derived from `status`
133- `isPaused: boolean`
134 - will be `true` if the mutation has been `paused`
135 - see [Network Mode](../../guides/network-mode) for more information.
136- `data: undefined | unknown`
137 - Defaults to `undefined`
138 - The last successfully resolved data for the mutation.
139- `error: null | TError`
140 - The error object for the query, if an error was encountered.
141- `reset: () => void`
142 - A function to clean the mutation internal state (i.e., it resets the mutation to its initial state).
143- `failureCount: number`
144 - The failure count for the mutation.
145 - Incremented every time the mutation fails.
146 - Reset to `0` when the mutation succeeds.
147- `failureReason: null | TError`
148 - The failure reason for the mutation retry.
149 - Reset to `null` when the mutation succeeds.
150- `submittedAt: number`
151 - The timestamp for when the mutation was submitted.
152 - Defaults to `0`.
153- `variables: undefined | TVariables`
154 - The `variables` object passed to the `mutationFn`.
155 - Defaults to `undefined`.