In React Query, mutation is a mechanism for executing asynchronous logic that may affect server data. For scenarios where you need to subscribe to mutation state changes, React Query provides several hooks for handling state and events.
Using the useMutation Hook
The useMutation hook is the primary tool in React Query for handling mutations. It not only allows you to execute an asynchronous function but also enables you to subscribe to various state changes of the mutation. These states include:
isLoading: set totruewhen the asynchronous operation is in progressisSuccess: set totruewhen the asynchronous operation completes successfullyisError: set totruewhen the asynchronous operation throws an errordata: contains the data from the successful response of the asynchronous operationerror: contains the error information when the asynchronous operation fails
Implementation Example
Suppose we have an API addUser for adding a new user. Here's how to use the useMutation hook to execute this API and subscribe to different responses based on its state changes:
jsximport React from 'react'; import { useMutation } from 'react-query'; function CreateUserComponent() { const { mutate, isLoading, isSuccess, isError, error } = useMutation(addUser, { // Add callbacks like `onSuccess`, `onError`, and `onSettled` here to handle specific events onSuccess: () => { console.log('User added successfully'); // Perform additional actions, such as updating the state or displaying notifications }, onError: (error) => { console.error('Error adding user:', error); // Handle errors, display error messages, etc. } }); const handleAddUser = () => { const userData = { name: 'John', email: 'john@example.com' }; mutate(userData); }; return ( <div> <button onClick={handleAddUser} disabled={isLoading}> Add User </button> {isLoading && <p>Adding user...</p>} {isSuccess && <p>User added!</p>} {isError && <p>Error: {error.message}</p>} </div> ); }
Explanation
mutatefunction: Used to trigger the mutation. It receives the data to pass to the asynchronous function.- State flags: Flags like
isLoading,isSuccess, etc., allow you to update the UI based on the mutation's different states. - Event callbacks: Callbacks like
onSuccess,onError, andonSettledallow you to execute additional logic when the mutation reaches specific states.
In this way, React Query provides a powerful and flexible approach to handling asynchronous data updates and rendering UI based on these state changes.