Performing Data Mutation with useMutation
Showcase how to update data on the server using the useMutation hook and reflect that update in the UI.
import { useMutation, useQueryClient } from 'react-query';
import axios from 'axios';
const updatePost = () => {
const queryClient = useQueryClient();
const mutation = useMutation(updatedPost => axios.put('/posts/1', updatedPost), {
onSuccess: () => {
// Invalidate and refetch
queryClient.invalidateQueries('posts');
},
});
return mutation;
};
This code defines a function that uses the useMutation hook to update a post on the server with a PUT request to '/posts/1'. On success, it invalidates the 'posts' query in the cache, triggering a refetch to update the UI with the latest data.
const { mutate, isLoading, isError, error } = updatePost();
const handleSubmit = (updatedPost) => {
mutate(updatedPost);
};
if (isLoading) console.log('Updating...');
if (isError) console.log('Error:', error.message);
This snippet uses the updatePost function to perform a mutation. It destructures mutate, isLoading, isError, and error from the useMutation hook. handleSubmit is used to call mutate with the updated post. Loading and error states are handled with console.log.