In React Query, the useMutation hook is used to trigger asynchronous functions (such as API calls) and can accept callback functions to handle various states during the process, such as success, error, or mutation. To display the response data from useMutation on the page, you can achieve this by utilizing the states and callback functions provided by this hook.
Here is a clear step-by-step example demonstrating how to use useMutation and display response data on the page:
- Create an asynchronous function: First, define a function that performs an asynchronous operation, typically an API call, returning a Promise.
javascriptconst createItem = async (newItem) => { const response = await fetch('/api/items', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(newItem), }); if (!response.ok) { throw new Error('Network response was not ok'); } return response.json(); };
- Use the
useMutationhook: Within the component, use theuseMutationhook and pass in the asynchronous function created in the previous step.
javascriptimport { useMutation } from 'react-query'; function MyComponent() { const mutation = useMutation(createItem); // ... }
- Trigger the Mutation on the page: Within the component, trigger the mutation through user interaction (such as clicking a button).
javascript<button onClick={() => mutation.mutate({name: 'New Item'})}> Create Item </button>
- Display the response data: Use the states and data returned by the
useMutationhook to display the results on the page. You can display different interfaces using states likemutation.isLoading,mutation.isError, andmutation.isSuccess, and access the response data throughmutation.data.
javascript// Display results on the page if (mutation.isLoading) { return <div>Creating item...</div>; } if (mutation.isError) { return <div>An error occurred: {mutation.error.message}</div>; } if (mutation.isSuccess) { return <div>Item created: {JSON.stringify(mutation.data)}</div>; } // Submit button return ( <> <button onClick={() => mutation.mutate({name: 'New Item'})}> Create Item </button> {mutation.status === 'success' ? <div>Item created: {JSON.stringify(mutation.data)}</div> : null} </> ); // ...
In the above code, we trigger the mutation using the mutate function and display different states based on mutation.isLoading, mutation.isError, and mutation.isSuccess. The response data is accessed via mutation.data and displayed on the page.
This approach allows React Query to simplify state management, eliminating the need for manual handling of loading or error states, and centralizing response data handling for cleaner, more organized code.