Blog>
Snippets

Custom Mutation Handlers

Demonstrate the implementation of custom mutation handlers to efficiently update the cache after a mutation, showcasing how to reflect the latest server state.
import { useMutation, useQueryClient } from 'react-query';
import axios from 'axios';

const useUpdateArticleTitle = (id) => {
  const queryClient = useQueryClient();
  return useMutation(
    newTitle => axios.patch(`/articles/${id}`, { title: newTitle }),
    {
      onSuccess: (data, variables, context) => {
        // Directly updating the cache with the new article data
        queryClient.setQueryData(['articles', id], data.data);
      },
      onMutate: async newTitle => {
        await queryClient.cancelQueries(['articles', id]);
        const previousArticle = queryClient.getQueryData(['articles', id]);
        // Optimistically update to the new value
        queryClient.setQueryData(['articles', id], prev => ({...prev, title: newTitle}));
        return { previousArticle };
      },
      onError: (err, newTitle, context) => {
        // Rollback to previous value on error
        queryClient.setQueryData(['articles', id], context.previousArticle);
      }
    }
  );
}
This code snippet demonstrates how to create a custom mutation handler using React Query to update the title of an article. It includes optimistic updates to immediately reflect changes in the UI and rollbacks in case of errors. The mutation is performed via an Axios PATCH request.