Blog>
Snippets

Fetching Data with useQuery Hook

Demonstrate fetching data from an API using the useQuery hook, including handling loading and error states, and displaying fetched data in a component.
import React from 'react';
import { useQuery } from '@tanstack/react-query';
First, import React along with the useQuery hook from React Query.
const fetchTodos = async () => {
  const response = await fetch('https://jsonplaceholder.typicode.com/todos');
  if (!response.ok) {
    throw new Error('Network response was not ok');
  }
  return response.json();
};
Define the fetch function that will be passed to the useQuery hook. This function fetches data from an API and returns a promise.
function Todos() {
  const { data, isLoading, isError, error } = useQuery(['todos'], fetchTodos);

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

  return (
    <ul>
      {data.map(todo => (
        <li key={todo.id}>{todo.title}</li>
      ))}
    </ul>
  );
}
The Todos component uses useQuery to fetch the todos list. It handles loading and error states, and renders the fetched data.