Fetching Data
The primary way to fetch data in a React application with Hyper-fetch is by using the useFetch hook. It's designed to
handle everything you need for data fetching: loading states, error handling, and of course, the data itself. This hook
simplifies your component logic by abstracting away the complexities of making and managing API requests.
- How to use the
useFetchhook to fetch data from an API. - How to handle loading and error states in your components.
- How to pass parameters to your requests.
- What are the main values returned by the
useFetchhook.
Basic Usage
To get started, you simply pass a request instance to the useFetch hook. It will automatically execute the request
when the component mounts.
function UserList() {
const { data: users, loading, error } = useFetch(getUsers);
if (loading) {
return <div className="p-4">Loading users...</div>;
}
if (error) {
return <div className="p-4 text-red-500">Oops! Something went wrong.</div>;
}
return (
<div className="p-4">
<h2 className="text-xl font-bold mb-2">Users</h2>
<ul className="list-disc list-inside">{users?.map((user) => <li key={user.id}>{user.name}</li>)}</ul>
</div>
);
}
Fetching with Parameters
Often, you'll need to fetch a specific resource by an identifier. You can pass parameters to your request using the
.setParams() method.
This example fetches a single user by their ID.
function UserProfile() {
const [userId, setUserId] = React.useState(1);
const { data: user, loading, error } = useFetch(getUser.setParams({ userId }));
const loadNextUser = () => {
setUserId((id) => id + 1);
};
return (
<div className="p-4 border rounded-md">
<div className="flex justify-between items-center mb-4">
<h2 className="text-xl font-bold">User Profile</h2>
<button className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600" onClick={loadNextUser}>
Load Next User
</button>
</div>
{loading && <div>Loading...</div>}
{error && <div className="text-red-500">Could not fetch user data.</div>}
{user && (
<div>
<p>
<span className="font-semibold">ID:</span> {user.id}
</p>
<p>
<span className="font-semibold">Name:</span> {user.name}
</p>
<p>
<span className="font-semibold">Email:</span> {user.email}
</p>
</div>
)}
</div>
);
}
The useFetch hook will automatically re-fetch the data whenever the userId state changes because Hyper-fetch tracks
the dependencies of your request.
Returned Values
The useFetch hook returns a rich set of values beyond just data, loading, and error:
const {
data, // The response data (typed)
error, // The error object if the request failed
loading, // Whether the request is in progress
success, // Whether the last request was successful
status, // HTTP status code
extra, // Adapter-specific extra data (e.g. response headers)
retries, // Number of retries performed
refetch, // Function to manually re-fetch data
abort, // Function to abort the current request
onSuccess, // Registrar for success callbacks
onError, // Registrar for error callbacks
onFinished, // Registrar for finished callbacks (success or error)
onRequestStart, // Registrar for request start callbacks
onAbort, // Registrar for abort callbacks
onOfflineError, // Registrar for offline error callbacks
setData, // Manually set the data state
setError, // Manually set the error state
setLoading, // Manually set the loading state
} = useFetch(getUsers);
Hook Options
You can pass a second argument to useFetch to configure its behavior:
const { data } = useFetch(getUser.setParams({ userId }), {
// Don't fetch on mount; only fetch when dependencies change
disabled: false,
// Keep showing previous data while a new request is loading
keepPreviousData: true,
// Custom dependencies array - re-fetch when these change
dependencies: [userId],
});
Key options include:
disabled: Whentrue, prevents the hook from fetching. Useful for conditional fetching.keepPreviousData: Preserves the previous response data while a re-fetch is in progress, avoiding UI flicker.dependencies: An array of values that trigger a re-fetch when they change (similar to React'suseEffectdeps).initialResponse: Provide initial data for SSR or hydration scenarios.
You've learned the basics of fetching data with useFetch!
- You can fetch lists of data and single items with parameters.
- You can handle loading and error states to provide a better user experience.
- You understand how
useFetchautomatically re-fetches when request parameters change. - You are ready to explore more advanced features of the
useFetchhook.
