Blog>
Snippets

Using the useQuery Hook for Data Fetching

Showcase how to use the useQuery hook to fetch data from an API, display the data in a component, and handle loading and error states.
import { useQuery } from '@tanstack/react-query';
import axios from 'axios';

// Function to fetch data
const fetchData = async () => {
  const { data } = await axios.get('https://api.example.com/data');
  return data;
};
This piece of code imports the useQuery hook from React Query and axios for making HTTP requests. It defines a fetchData function that asynchronously fetches data from an example API.
const DataFetchingComponent = () => {
  // Using the useQuery hook to fetch data
  const { isLoading, isError, error, data } = useQuery(['data'], fetchData);

  // Loading state
  if (isLoading) return <div>Loading...</div>;

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

  // Display data
  return (
    <div>
      {data.map(item => (
        <div key={item.id}>{item.title}</div>
      ))}
    </div>
  );
};
This component uses the useQuery hook to fetch data using the fetchData function. It handles loading and error states, displaying appropriate messages, and renders the fetched data.