Blog>
Snippets

Updating a User Profile with useMutation

Demonstrate how to use the useMutation hook to update a user's profile information on a server and optimistically update the UI to reflect the changes immediately.
import { useMutation, useQueryClient } from 'react-query';
import axios from 'axios';
Imports necessary from react-query and axios for making HTTP requests.
const useUpdateUserProfile = () => {
  const queryClient = useQueryClient();
  return useMutation(
    userData => axios.put('/api/user/profile', userData),
    {
      onMutate: async newUserProfile => {
        await queryClient.cancelQueries('userProfile');
        const previousUserProfile = queryClient.getQueryData('userProfile');
        queryClient.setQueryData('userProfile', old => ({ ...old, ...newUserProfile }));
        return { previousUserProfile };
      },
      onError: (err, newUserProfile, context) => {
        queryClient.setQueryData('userProfile', context.previousUserProfile);
      },
      onSettled: () => {
        queryClient.invalidateQueries('userProfile');
      },
    }
  );
};
Defines a custom hook using useMutation for updating a user's profile. It optimistically updates the UI before the mutation is completed and rolls back on error.
const { mutate: updateUserProfile } = useUpdateUserProfile();

updateUserProfile({ name: 'John Doe', email: 'john.doe@example.com' });
How to use the custom hook in a component to update a user's profile. It triggers the mutation with new user data.