To use the useQuery
hook for data fetching with React-Query, you first need to define a query function that fetches the data you need. Then, you can use the useQuery
hook in your React components to fetch and manage that data. Here's a step-by-step guide:
bashnpm install react-query
fetch
, Axios, or any other HTTP library.For example, let's create a query function that fetches a list of users from an API:
javascriptconst fetchUsers = async () => {
const response = await fetch('https://api.example.com/users');
if (!response.ok) {
throw new Error('Failed to fetch users');
}
return response.json();
};
useQuery
hook from React-Query and use it in your component to fetch and manage the data.javascriptimport { useQuery } from 'react-query';
const UsersComponent = () => {
const { data, isLoading, error } = useQuery('users', fetchUsers);
if (isLoading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
return (
<div>
<h1>Users</h1>
<ul>
{data.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
</div>
);
};
export default UsersComponent;
In this example:
useQuery
hook to fetch data from the 'users'
query key using the fetchUsers
function.isLoading
variable indicates whether the query is currently loading.error
variable contains any error that occurred during data fetching.With this setup, your React components will fetch and manage data using the useQuery
hook from React-Query, providing a powerful and efficient way to manage data fetching in your application.