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

useMutation.md

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