Basic Data Fetching with useQuery Hook
Demonstrates fetching a list of users from an API and displaying it, handling loading and error states.
import { useQuery } from 'react-query';
import axios from 'axios';
// Fetching data function
const fetchUsers = async () => {
const { data } = await axios.get('https://jsonplaceholder.typicode.com/users');
return data;
};
This piece of code imports necessary dependencies and defines the asynchronous function fetchUsers to fetch data from the API.
const UsersList = () => {
const { data: users, error, isLoading } = useQuery('users', fetchUsers);
if (isLoading) return <div>Loading...</div>;
if (error) return <div>An error occurred: {error.message}</div>;
return (
<ul>
{users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
};
export default UsersList;
This component uses the useQuery hook from React Query to fetch and display a list of users. It handles loading states and potential errors.