Fetching and Displaying Data
Demonstrate how to use the `useQuery` hook to fetch data from an API and display it in a component, handling loading and error states.
import { useQuery } from '@tanstack/react-query';
import React from 'react';
First, import the useQuery hook from React Query and React.
const fetchUsers = async () => {
const response = await fetch('https://jsonplaceholder.typicode.com/users');
if (!response.ok) {
throw new Error('Network response was not ok.');
}
return response.json();
};
Define an asynchronous function to fetch users from the API.
function UsersComponent() {
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 component that uses the useQuery hook to fetch and display the users. It handles loading and error states.