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