Blog>
Snippets

Mutating Data with useMutation Hook

Demonstrate how to use the useMutation hook to update data on the server and then automatically invalidate related queries to refresh the UI with updated data.
import { useMutation, useQueryClient } from 'react-query';
import axios from 'axios';
Imports necessary hooks from React Query and axios for making HTTP requests.
const queryClient = useQueryClient();
Initializes the queryClient to interact with React Query's cache.
const updateTodo = useMutation(
  (todo) => axios.put(`/todos/${todo.id}`, todo),
  {
    onSuccess: () => {
      // Invalidate and refetch todos query to reflect updated data
      queryClient.invalidateQueries('todos');
    },
  }
);
Define a mutation for updating a todo item. On success, it automatically invalidates the 'todos' query to refresh the UI with the updated data.
const handleUpdate = (todo) => {
  updateTodo.mutate({ id: todo.id, title: 'Updated Title' });
};
Function to be called on a user action, e.g., clicking an update button. It executes the mutation with the new todo data.