Blog>
Snippets

Fetching Data with useQuery

Showcase how to use the useQuery hook to fetch data from an API, including handling loading, error states, and displaying the fetched data.
import { useQuery } from 'react-query';
import axios from 'axios';
First, import the necessary modules: useQuery from react-query for the data fetching, and axios for making the HTTP request.
const fetchPosts = async () => {
  const { data } = await axios.get('https://jsonplaceholder.typicode.com/posts');
  return data;
};
Define an asynchronous function fetchPosts to retrieve posts from the JSONPlaceholder API using axios. The function returns the fetched posts.
const Posts = () => {
  const { isLoading, error, data } = useQuery('posts', fetchPosts);

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

  return (
    <ul>
      {data.map(post => (
        <li key={post.id}>{post.title}</li>
      ))}
    </ul>
  );
};
Use the useQuery hook within a functional component to fetch posts. The hook is provided with a unique key 'posts' and the fetchPosts function. Depending on the hook's state, display loading message, error message, or a list of fetched posts.