Blog>
Snippets

Managing Mutations with useMutation

Illustrate the use of the useMutation hook to handle POST requests (creating new resources) and automatically update the UI based on the mutation's success or failure.
import { useMutation, useQueryClient } from 'react-query';
import axios from 'axios';
Imports necessary functionalities from react-query and axios for making HTTP requests.
const CreatePost = () => {
  const queryClient = useQueryClient();
  const mutation = useMutation(newPost => axios.post('/posts', newPost), {
    onSuccess: () => {
      queryClient.invalidateQueries('posts');
    },
  });

  const handleSubmit = async (event) => {
    event.preventDefault();
    const newPost = { title: 'React Query', body: 'Using useMutation hook to create a post.' };
    mutation.mutate(newPost);
  };

  return (
    <form onSubmit={handleSubmit}>
      <button type='submit'>Create Post</button>
    </form>
  );
};

export default CreatePost;
Defines a component to create a new post by using useMutation. In the onSuccess option of useMutation, we invalidate the posts query to refresh the list of posts after a successful create operation, ensuring the UI is automatically updated.
if (mutation.isLoading) {
  return <p>Submitting...</p>;
}
Shows a loading message while the mutation is in progress. This block of code should be placed within the component's return statement to provide feedback to the user.
if (mutation.isError) {
  return <p>An error occurred: {mutation.error.message}</p>;
}
Handles any errors that occur during the mutation. It should also be placed within the component's return statement to provide feedback to the user in case of an error.
if (mutation.isSuccess) {
  return <p>Post created successfully!</p>;
}
Confirms that the post was created successfully. This portion of the code also goes within the component's return method and provides positive feedback to the user upon successful creation of a post.