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