Blog>
Snippets

Using invalidateQueries for Refreshing Related Data

Demonstrate using `invalidateQueries` to refresh related queries after a data mutation occurs, ensuring data consistency across the application.
const { mutate } = useMutation(addNewComment, {
  onSuccess: () => {
    // After successfully adding a new comment
    queryClient.invalidateQueries(['comments']);
  },
});
This code snippet demonstrates how to use useMutation hook from React Query to add a new comment. onSuccess, it invalidates queries related to 'comments' forcing them to refetch and thus refresh with the latest data. This ensures consistency across the application after the mutation occurs.
const updatePost = async (newPost) => {
  await api.updatePost(newPost);
  // Invalidate queries related to 'posts' to ensure data is fresh
  queryClient.invalidateQueries(['posts']);
};
In this example, after updating a post through an API call, invalidateQueries is called on 'posts' queries. This action ensures that any component or hook relying on this data throughout the application will re-fetch the data, thus reflecting the most recent updates.