In React Query, when executing mutations (such as adding, updating, or deleting data), you can effortlessly monitor and display loading states by using the useMutation hook. The useMutation hook returns an object containing multiple properties and methods, including tools for managing and accessing mutation states.
How to Display Loading States Using useMutation
-
Setting Up the Mutation: First, define a mutation function that performs the actual data operations, such as API calls.
-
Using the
useMutationHook: In your component, pass the above mutation function touseMutationto receive a mutation object that includes methods and states for controlling the mutation. -
Retrieving and Using the
isLoadingState: The object returned byuseMutationcontains anisLoadingproperty, which istrueduring mutation execution and becomesfalseafter completion. You can leverage this property to display a loading indicator in the UI.
Example Code
Assume we have an API function for adding a user; we can use useMutation to add a user and display loading states as follows:
jsximport { useMutation } from 'react-query'; function addUser(userData) { return fetch('/api/users', { method: 'POST', body: JSON.stringify(userData), headers: { 'Content-Type': 'application/json', }, }).then(res => res.json()); } function CreateUserComponent() { const { mutate, isLoading } = useMutation(addUser); const handleAddUser = userData => { mutate(userData); }; return ( <div> <button onClick={() => handleAddUser({ name: 'John Doe' })}> Add User </button> {isLoading && <p>Loading...</p>} </div> ); }
In this example:
- We define an
addUserfunction that handles sending a POST request to the server. - In the component, we use
useMutationand pass theaddUserfunction. - We destructure to obtain
mutateandisLoading. - When the button is clicked,
handleAddUseris invoked, triggering the mutation viamutate. - Based on the value of
isLoading, we display a loading message in the UI.
By implementing this approach, you can provide users with clear feedback during asynchronous operations, thereby enhancing the overall user experience.