Blog>
Snippets

Fetching Data with React Query

Demonstrate how to use React Query to fetch, cache, and update data in a React component, utilizing the useQuery hook for a REST API call.
import { useQuery } from 'react-query';
import axios from 'axios';
First, import useQuery from React Query and axios for making API calls.
const fetchPosts = async () => {
  const { data } = await axios.get('https://jsonplaceholder.typicode.com/posts');
  return data;
};
Define an asynchronous function fetchPosts to fetch data from the API.
function Posts() {
  const { data, error, isLoading } = useQuery('posts', fetchPosts);

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

  return (
    <div>
      {data.map(post => (
        <p key={post.id}>{post.title}</p>
      ))}
    </div>
  );
}
Use the useQuery hook within your component to invoke fetchPosts. Utilize the returned data, error, and isLoading values to handle the UI state.