Performing a Mutation with useMutation Hook
Provide an example of using the useMutation hook to post data to an API and update the UI based on the mutation's success.
import { useMutation, useQueryClient } from 'react-query';
export function CreatePostButton() {
const queryClient = useQueryClient();
const { mutate, isLoading, error } = useMutation(
async (newPost) => {
const response = await fetch('https://api.example.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(newPost),
});
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
},
{
onSuccess: () => {
// Invalidate and refetch
queryClient.invalidateQueries('posts');
},
}
);
return (
<div>
{error && <span>Error posting the new post</span>}
<button
onClick={() => mutate({ title: 'New Post', content: 'This is a new post.' })}
disabled={isLoading}
>
Create Post
</button>
</div>
);
}
This code example demonstrates how to use the useMutation hook from React Query to post new data to an API endpoint. It creates a 'CreatePostButton' component that, when clicked, sends a POST request to create a new post. It uses the useMutation hook to handle the API request and automatically invalidates the 'posts' query cache to refresh the list of posts upon success. Error handling and loading state feedback are also included.