Blog>
Snippets

Updating Server Data with the useMutation Hook

Use the useMutation hook to update data on the server, handle the mutation state to provide user feedback, and invalidate queries to refresh related data.
import { useMutation, useQueryClient } from 'react-query';
import axios from 'axios';

function UpdateUser() {
  const queryClient = useQueryClient();
  const { mutate, isLoading, error } = useMutation(
    updatedUser => axios.put('https://jsonplaceholder.typicode.com/users', updatedUser),
    {
      onSuccess: () => {
        // Invalidate and refetch
        queryClient.invalidateQueries('users');
      }
    }
  );

  const updateUser = (userData) => {
    mutate(userData);
  };

  if (isLoading) return <p>Updating...</p>;
  if (error) return <p>An error occurred: {error.message}</p>;

  return (
    <button onClick={() => updateUser({ id: 1, name: 'John Doe' })}>Update User</button>
  );
}
This code demonstrates how to use the useMutation hook from React Query to update user data on the server. It utilizes axios for making HTTP requests. Upon a successful mutation, it invalidates the 'users' query to ensure the UI is synchronized with the latest data. Loading and error states are managed to give feedback to the user.