Blog>
Snippets

Fetching Data with useQuery Hook

Show a basic example of using the useQuery hook to fetch data from an API and display it in a component, handling loading and error states.
import { useQuery } from 'react-query';
import React from 'react';
First, import useQuery from react-query and React.
const fetchUsers = async () => {
  const response = await fetch('https://api.example.com/users');
  if (!response.ok) {
    throw new Error('Network response was not ok');
  }
  return response.json();
};
Define an async function to fetch users data from an API.
function Users() {
  const { data, error, isLoading } = useQuery('users', fetchUsers);

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

  return (
    <ul>
      {data.map(user => (
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  );
}
Create a Users component where useQuery is used for fetching data. It handles loading and error states.