Basic Use of useQuery Hook for Data Fetching
Demonstrate the basic setup and use of the useQuery hook to fetch a list of items from an API and display them.
import { useQuery } from 'react-query';
import axios from 'axios';
Imports the useQuery hook from react-query and axios for making HTTP requests.
const fetchItems = async () => {
const { data } = await axios.get('https://api.example.com/items');
return data;
};
Defines an asynchronous function to fetch items from an API.
const ItemsComponent = () => {
const { isLoading, error, data } = useQuery('items', fetchItems);
if (isLoading) return <div>Loading...</div>;
if (error) return <div>An error occurred: {error.message}</div>;
return (
<ul>
{data.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
);
};
Defines a component that uses the useQuery hook to fetch items and display them. It handles loading and error states.