Blog>
Snippets

Query Invalidation and Data Synchronization

Demonstrate how to invalidate and refetch queries automatically after data mutations to ensure UI consistency with server state.
import { useQuery, useMutation, useQueryClient } from 'react-query';
import axios from 'axios';

const updatePost = async (postData) => {
  const { data } = await axios.put(`/api/posts/${postData.id}`, postData);
  return data;
};
This code snippet imports necessary hooks from React Query and axios for making HTTP requests. It defines an asynchronous function `updatePost` to update a post using a PUT request, where `postData` contains the updated information for a specific post including its `id`.
const Posts = () => {
  const queryClient = useQueryClient();
  const { data: posts, refetch } = useQuery('posts', () => axios.get('/api/posts').then(res => res.data));

  const { mutate } = useMutation(updatePost, {
    onSuccess: () => {
      // Invalidate and refetch
      queryClient.invalidateQueries('posts');
    },
  });

  const handleUpdate = async (postData) => {
    mutate(postData);
  };

  return (
    // Render posts and handle update
  );
};
This component fetches posts using `useQuery` and updates a post with `useMutation`. After a post is successfully updated (`onSuccess`), `invalidateQueries` is called to mark the 'posts' query as invalidated. This causes React Query to refetch the posts, ensuring the UI aligns with the latest server state.