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

useMutation.md

146 lines7.1 KB

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