Blog>
Snippets

Performing a POST Request with useMutation Hook

Shows how to create a new user on the server using the useMutation hook, including optimistic update.
import { useMutation, useQueryClient } from 'react-query';
import axios from 'axios';
First, import useMutation and useQueryClient from react-query, and axios for making HTTP requests.
const useCreateUser = () => {
  const queryClient = useQueryClient();
  return useMutation(
    newUser => axios.post('/users', newUser),
    {
      // On mutation success
      onSuccess: () => {
        // Invalidate and refetch
        queryClient.invalidateQueries('users');
      },
      // Optimistic update
      onMutate: async newUser => {
        await queryClient.cancelQueries('users');
        const previousUsers = queryClient.getQueryData('users');

        queryClient.setQueryData('users', old => [...old, newUser]);

        return { previousUsers };
      },
      // Revert optimistic update on error
      onError: (err, newUser, context) => {
        queryClient.setQueryData('users', context.previousUsers);
      }
    }
  );
};
Defines a custom hook, useCreateUser, which utilizes the useMutation hook for posting new user data. This example includes optimistic updates where the cache is updated immediately to reflect the new state before the HTTP request completes. If an error happens, it reverts back to the previous state.
const CreateUserComponent = () => {
  const { mutate } = useCreateUser();

  const handleSubmit = e => {
    e.preventDefault();
    const formData = new FormData(e.target);
    const newUser = Object.fromEntries(formData.entries());
    mutate(newUser); // Trigger mutation
  };

  return (
    <form onSubmit={handleSubmit}>
      <input name="name" placeholder="Name" required />
      <input name="email" placeholder="Email" required />
      <button type="submit">Create User</button>
    </form>
  );
};
A React component that provides a form for creating a new user. It uses the custom hook defined earlier to trigger the mutation when the form is submitted.