Creating a React Component with the useGetUsersQuery Hook
Show the usage of an auto-generated hook, such as `useGetUsersQuery`, within a functional React component to fetch and display a list of users, illustrating loading, error, and data states.
import React from 'react';
import { useGetUsersQuery } from './services/users';
const UsersList = () => {
// Invoke the auto-generated hook to fetch users
const { data: users, error, isLoading } = useGetUsersQuery();
// Show loading state
if (isLoading) return <div>Loading...</div>;
// Handle possible error
if (error) return <div>Error: {error.message}</div>;
// Render the list of users
return (
<ul>
{users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
};
export default UsersList;
This code defines a UsersList React functional component which utilizes a custom hook called useGetUsersQuery (presumably auto-generated by a tool like RTK Query) to fetch a list of users from an API. It handles the loading state, errors, and displays the list of users once the data is successfully fetched. The 'users' returned by the hook is iterated over to display each user's name within an unordered list.