Blog>
Snippets

Posting a Comment and Invalidating Cache

Show how to post a new comment using useMutation, and then invalidate the cache of related queries to ensure the comment list is refreshed with the latest data.
import { useMutation, useQueryClient } from 'react-query';
import axios from 'axios';

const usePostComment = () => {
    const queryClient = useQueryClient();
    return useMutation(comment => axios.post('/api/comments', comment), {
        onSuccess: () => {
            // Invalidate and refetch
            queryClient.invalidateQueries('comments');
        }
    });
};
This code defines a custom hook usePostComment using useMutation to post a new comment. Upon a successful mutation, the onSuccess callback invalidates the cache for the 'comments' query, triggering a refetch to update the UI with the latest comments.
const { mutate } = usePostComment();

mutate({ text: 'Awesome post!', postId: 1 });
This code demonstrates how to use the usePostComment hook within a component to post a new comment. It calls the mutate function with the new comment's data.