Blog>
Snippets

Caching and Updating Data with React Query

Provide an example of how React Query's caching mechanisms are used to cache fetched data and how to invalidate the cache to update data when the underlying server state changes.
import { useQuery, useMutation, useQueryClient } from 'react-query';

async function fetchPosts() {
  const response = await fetch('https://api.example.com/posts');
  if (!response.ok) {
    throw new Error('Network response was not ok');
  }
  return response.json();
}
Defines a function to fetch posts data from a server using the Fetch API. Utilizes React Query's `useQuery` hook to manage and cache the fetching process.
function PostsComponent() {
  const { data, isLoading, error } = useQuery('posts', fetchPosts);

  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>An error occurred: {error.message}</div>;

  return (
    <ul>
      {data.map(post => (
        <li key={post.id}>{post.title}</li>
      ))}
    </ul>
  );
}
Creates a React component that uses the `useQuery` hook to fetch posts. It displays a loading message while data is being fetched, handles potential errors, and renders the list of posts once data loading is complete.
async function updatePost(postId, updatedPost) {
  const response = await fetch(`https://api.example.com/posts/${postId}`, {
    method: 'PUT',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(updatedPost),
  });

  return response.json();
}
Defines a function that updates a post on the server using the Fetch API with a PUT request. This function is meant to be used with a React Query mutation.
function useUpdatePost() {
  const queryClient = useQueryClient();

  return useMutation(updatePost, {
    onSuccess: () => {
      queryClient.invalidateQueries('posts');
    },
  });
}
Defines a custom hook using React Query's `useMutation` hook for updating a post. On a successful update, it invalidates the 'posts' query to ensure fresh data is fetched reflecting the update.