Blog>
Snippets

Fetching Data with useQuery in React Components

Show how to use the useQuery hook to fetch data from an API, handle loading states and errors, and display the fetched data in a React component.
import { useQuery } from '@tanstack/react-query';
import React from 'react';
This is the import statement. It imports the useQuery hook from React Query, and React to enable the creation of the component.
async function fetchPosts() {
  return await fetch('https://jsonplaceholder.typicode.com/posts').then(res => res.json());
}
Defines an asynchronous function that fetches data from an API endpoint. The function uses the fetch API, waits for the response, converts it to JSON, and returns the data.
function PostsComponent() {
  const { isLoading, isError, error, data: posts } = useQuery(['posts'], fetchPosts);

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

  return (
    <div>
      {posts.map((post) => (
        <p key={post.id}>{post.title}</p>
      ))}
    </div>
  );
}
This function component uses the useQuery hook to fetch posts. It destructures isLoading, isError, error, and data from the useQuery hook. It handles loading states by checking `isLoading`, displays an error message if `isError` is true, and maps through the `posts` data to display post titles.
export default PostsComponent;
Exports the PostsComponent so it can be used in other parts of the application.