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