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

useMutation.md

141 lines7.0 KB

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