useMutation
React hook to execute asynchronous mutations with loading, error, and data states alongside success and error callbacks.
Demo
Usage
Shorthand — mutationFn + optional callbacks:
Object form:
Parameters
Shorthand form
| Parameter | Type | Description |
|---|---|---|
mutationFn | (variables: V) => Promise<T> | Async function that performs the mutation. |
callbacks.onSuccess | (data: T, variables: V) => void | Called when the mutation resolves. |
callbacks.onError | (error: Error, variables: V) => void | Called when the mutation rejects. |
Object form
| Property | Type | Description |
|---|---|---|
mutationFn | (variables: V) => Promise<T> | Async function that performs the mutation. |
onSuccess | (data: T, variables: V) => void | Called when the mutation resolves. |
onError | (error: Error, variables: V) => void | Called when the mutation rejects. |
Return Values
Returns a tuple [mutate, state]:
| Type | Description | |
|---|---|---|
mutate | (variables: V) => Promise<void> | Triggers the mutation with the given variables. |
state.data | T | null | Last resolved value, or null before first success. |
state.loading | boolean | true while the mutation is in flight. |
state.error | Error | null | Last error, or null if the last call succeeded. |
state.reset | () => void | Resets data, loading and error to their initial values. |