React Query is a powerful library for data fetching, caching, and updating, enabling developers to efficiently manage data. In React Query, we typically use the useQuery hook for automatically fetching data and handling updates, or the useMutation hook for executing operations such as POST, PUT, and PATCH that modify server state. However, sometimes we need to trigger requests only upon specific user interactions, such as button click events.
To trigger requests in button click events, we typically use the useMutation hook from React Query. This hook allows us to define a function that triggers asynchronous requests and executes callback functions upon success, failure, or error.
Here is an example. Suppose we have a feature to create a new user via an API, and we want to trigger this creation request when a button is clicked:
jsximport { useMutation } from 'react-query'; // This function handles the request to the server const createUser = async (userData) => { const response = await fetch('/api/users', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(userData), }); if (!response.ok) { throw new Error('Error creating user'); } return response.json(); }; function MyComponent() { // Use the useMutation hook to define the mutation and provide the createUser function const mutation = useMutation(createUser, { onSuccess: (data) => { // Callback function when the request succeeds console.log('User created!', data); }, onError: (error) => { // Callback function when the request fails console.error('Error creating user', error); }, }); // This function is called when the button is clicked const handleCreateUserClick = () => { // Assume newUser is the data to submit const newUser = { name: 'Jane Doe', email: 'jane.doe@example.com' }; // Trigger the request using mutation.mutate mutation.mutate(newUser); }; return ( <div> <button onClick={handleCreateUserClick}>Create User</button> {mutation.isLoading && <span>Creating user...</span>} {mutation.isError && <span>An error occurred: {mutation.error.message}</span>} {mutation.isSuccess && <span>User created successfully!</span>} </div> ); }
In this example, we first define an asynchronous createUser function that sends a POST request to the server with the new user data. Then, in our component, we use the useMutation hook to create a mutation object, passing the createUser function and some callback functions. In the button's click event handler handleCreateUserClick, we trigger the request using mutation.mutate.
The mutation object also provides status flags and data that we can use to display the request status to the user, such as whether it is loading (isLoading), if an error occurred (isError), if it was successful (isSuccess), and the error itself (error). This allows us to provide appropriate feedback in the UI.