Blog>
Snippets

Performing Mutations with the useMutation Hook

Showcase an example of how to use React Query's useMutation hook to make a POST request for submitting form data and updating the UI based on the response.
import { useMutation, useQueryClient } from 'react-query';
import axios from 'axios';
Importing the necessary hooks from React Query and axios for making HTTP requests.
const addTodo = async (newTodo) => {
  const { data } = await axios.post('/api/todos', newTodo);
  return data;
};
Defines an asynchronous function that submits the new todo item to the server and returns the response.
const TodoForm = () => {
  const queryClient = useQueryClient();
  const mutation = useMutation(addTodo, {
    onSuccess: () => {
      // Invalidate and refetch todos
      queryClient.invalidateQueries('todos');
    },
  });

  const handleSubmit = (e) => {
    e.preventDefault();
    // Extract form data and call the mutation
    const formData = /* extract data from form elements */;
    mutation.mutate(formData);
  };

  return (
    // Form JSX goes here
    // For simplicity, the form setup is not shown
  );
};
Sets up the useMutation hook with an onSuccess option to refetch todos upon a successful submission. It also includes a form handler to call the mutation with form data.