Overview
TheuseApiMutation hook is a wrapper around Convex’s useMutation hook that provides automatic pending state management for mutation operations. It simplifies handling loading states during API mutations and provides a consistent interface for executing mutations with proper error handling.
Usage
Parameters
The Convex mutation function to be executed. Typically imported from your Convex API definitions.
Return Value
The hook returns an object with the following properties:An async function that executes the mutation with the provided payload. Returns a promise that resolves with the mutation result or rejects with an error.
A boolean flag indicating whether the mutation is currently in progress. Use this to disable buttons or show loading states.
Real-World Examples
Creating a Board
Favoriting/Unfavoriting Items
Implementation Details
The hook internally:- Maintains a local
pendingstate using React’suseState - Wraps the Convex mutation in a custom
mutatefunction - Sets
pendingtotruebefore executing the mutation - Resets
pendingtofalseafter the mutation completes (success or failure) - Preserves the original promise chain for result handling
The
pending state is automatically managed - it’s set to true when the mutation starts and false when it completes, regardless of success or failure.Best Practices
- Use the
pendingstate to disable UI elements during mutations - Always handle both success and error cases in your promise chain
- Provide user feedback through toast notifications or other UI indicators
- Destructure with custom names when using multiple mutations in the same component