Basic Data Fetching using useQuery
Demonstrate how to fetch data from an API using the useQuery hook, including the handling of loading, error, and data states.
import { useQuery } from 'react-query';
import axios from 'axios';
Import the useQuery hook from React Query and axios for making API calls.
const fetchPosts = async () => {
const { data } = await axios.get('https://jsonplaceholder.typicode.com/posts');
return data;
};
Define an asynchronous function to fetch posts from the JSONPlaceholder API.
const PostsComponent = () => {
const { isLoading, error, data } = useQuery('posts', fetchPosts);
if (isLoading) return <div>Loading...</div>;
if (error) return <div>An error has occurred: {error.message}</div>;
return (
<ul>
{data.map(post => (
<li key={post.id}>{post.title}</li>
))}
</ul>
);
};
Use the useQuery hook to fetch data. Handle loading, error, and data states by conditionally rendering different UI elements.