- manage loading state easily
function UserComponent() {
const [request, isLoading] = useRequestState(fetchData);
return (
<div>
<h1>User Component</h1>
<p>Current userId: {userId}</p>
<button onClick={() => request(userId)} disabled={isLoading}>
{isLoading ? 'Loading...' : 'Fetch Data'}
</button>
{isLoading && <p>Loading...</p>}
</div>
);
}
- Pass fetch function parameters for versatile usage
function PlanComponent() {
const [request, isLoading, requestedPlan] = useRequestState(fetchData);
const isPlanALoading = isLoading && requestedPlan === 'planA';
const isPlanBLoading = isLoading && requestedPlan === 'planB';
return (
<div>
<h1>User Component</h1>
<p>Current userId: {userId}</p>
<button onClick={() => request('planA')} disabled={isPlanALoading}>
{isPlanALoading ? 'Loading...' : 'Fetch Data'}
</button>
<button onClick={() => request('planB')} disabled={isPlanBLoading}>
{isPlanBLoading ? 'Loading...' : 'Fetch Data'}
</button>
{isLoading && <p>Loading...</p>}
</div>
);
}