Dependent Requests
In many applications, you'll encounter scenarios where one request depends on the data returned by another. For example,
you might need to fetch a user's profile first and then use their ID to fetch their posts. Hyper-fetch provides a simple
and declarative way to handle these dependent requests using the disabled option in the useFetch hook.
- How to create dependent requests where one query relies on data from another.
- How to use the
disabledoption to conditionally prevent a request from firing. - How to build a chain of requests for more complex data-fetching scenarios.
Chaining Requests
The key to handling dependent requests is the disabled option in the useFetch hook. By setting disabled to true,
you can prevent a request from being executed. When the condition changes and disabled becomes false, the request
will automatically fire.
Let's look at an example where we first fetch a user and then, once we have the user's ID, we fetch their products.
function DependentRequestsExample() {
const { data: user } = useFetch(getCurrentUser);
const {
data: products,
loading,
error,
} = useFetch(getUserProducts.setParams({ userId: user?.id }), {
disabled: !user,
});
return (
<div className="flex flex-col gap-4">
{user ? (
<div className="p-4 border rounded-md">
<p className="font-bold">User Details:</p>
<p>ID: {user.id}</p>
<p>Name: {user.name}</p>
</div>
) : (
<p>Loading user...</p>
)}
{loading && <p>Loading products...</p>}
{error && <p className="text-red-500">Error loading products!</p>}
{products && (
<div className="p-4 border rounded-md">
<p className="font-bold">Products:</p>
<ul className="list-disc list-inside">
{products.map((product) => (
<li key={product.id}>{product.name}</li>
))}
</ul>
</div>
)}
</div>
);
}
In this example:
- The first
useFetchcall fetches the current user. - The second
useFetchcall for products is disabled as long asuserisundefined. - Once the first request succeeds and
userdata is available, thedisabled: !usercondition becomesfalse. - The second request then automatically executes with the
userIdfrom theuserobject.
This pattern ensures that you don't try to fetch data with missing parameters, which would likely result in an error.
You've mastered handling dependent requests in Hyper-fetch!
- You can chain requests by using data from one request to trigger another.
- You can use the
disabledoption for conditional fetching. - You can build complex data-fetching logic in a declarative and readable way.
