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

useMutation.md

106 lines5.1 KB

1---
2id: useMutation
3title: useMutation
4---
5​
6```js
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 mutationKey,
21 onError,
22 onMutate,
23 onSettled,
24 onSuccess,
25 retry,
26 retryDelay,
27 useErrorBoundary,
28 meta,
29})
30​
31mutate(variables, {
32 onError,
33 onSettled,
34 onSuccess,
35})
36```
37​
38**Options**
39​
40- `mutationFn: (variables: TVariables) => Promise<TData>`
41 - **Required**
42 - A function that performs an asynchronous task and returns a promise.
43 - `variables` is an object that `mutate` will pass to your `mutationFn`
44- `mutationKey: string`
45 - Optional
46 - A mutation key can be set to inherit defaults set with `queryClient.setMutationDefaults` or to identify the mutation in the devtools.
47- `onMutate: (variables: TVariables) => Promise<TContext | void> | TContext | void`
48 - Optional
49 - This function will fire before the mutation function is fired and is passed the same variables the mutation function would receive
50 - Useful to perform optimistic updates to a resource in hopes that the mutation succeeds
51 - 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.
52- `onSuccess: (data: TData, variables: TVariables, context?: TContext) => Promise<unknown> | void`
53 - Optional
54 - This function will fire when the mutation is successful and will be passed the mutation's result.
55 - If a promise is returned, it will be awaited and resolved before proceeding
56- `onError: (err: TError, variables: TVariables, context?: TContext) => Promise<unknown> | void`
57 - Optional
58 - This function will fire if the mutation encounters an error and will be passed the error.
59 - If a promise is returned, it will be awaited and resolved before proceeding
60- `onSettled: (data: TData, error: TError, variables: TVariables, context?: TContext) => Promise<unknown> | void`
61 - Optional
62 - This function will fire when the mutation is either successfully fetched or encounters an error and be passed either the data or error
63 - If a promise is returned, it will be awaited and resolved before proceeding
64- `retry: boolean | number | (failureCount: number, error: TError) => boolean`
65 - Defaults to `0`.
66 - If `false`, failed mutations will not retry.
67 - If `true`, failed mutations will retry infinitely.
68 - If set to an `number`, e.g. `3`, failed mutations will retry until the failed mutations count meets that number.
69- `retryDelay: number | (retryAttempt: number, error: TError) => number`
70 - This function receives a `retryAttempt` integer and the actual Error and returns the delay to apply before the next attempt in milliseconds.
71 - A function like `attempt => Math.min(attempt > 1 ? 2 ** attempt * 1000 : 1000, 30 * 1000)` applies exponential backoff.
72 - A function like `attempt => attempt * 1000` applies linear backoff.
73- `useErrorBoundary: undefined | boolean | (error: TError) => boolean`
74 - Defaults to the global query config's `useErrorBoundary` value, which is `undefined`
75 - Set this to `true` if you want mutation errors to be thrown in the render phase and propagate to the nearest error boundary
76 - Set this to `false` to disable the behavior of throwing errors to the error boundary.
77 - 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`)
78- `meta: Record<string, unknown>`
79 - Optional
80 - 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`).
81​
82**Returns**
83​
84- `mutate: (variables: TVariables, { onSuccess, onSettled, onError }) => void`
85 - The mutation function you can call with variables to trigger the mutation and optionally override options passed to `useMutation`.
86 - `variables: TVariables`
87 - Optional
88 - The variables object to pass to the `mutationFn`.
89 - Remaining options extend the same options described above in the `useMutation` hook.
90 - If you make multiple requests, `onSuccess` will fire only after the latest call you've made.
91- `mutateAsync: (variables: TVariables, { onSuccess, onSettled, onError }) => Promise<TData>`
92 - Similar to `mutate` but returns a promise which can be awaited.
93- `status: string`
94 - Will be:
95 - `idle` initial status prior to the mutation function executing.
96 - `loading` if the mutation is currently executing.
97 - `error` if the last mutation attempt resulted in an error.
98 - `success` if the last mutation attempt was successful.
99- `isIdle`, `isLoading`, `isSuccess`, `isError`: boolean variables derived from `status`
100- `data: undefined | unknown`
101 - Defaults to `undefined`
102 - The last successfully resolved data for the query.
103- `error: null | TError`
104 - The error object for the query, if an error was encountered.
105- `reset: () => void`
106 - A function to clean the mutation internal state (i.e., it resets the mutation to its initial state).