Question: How do I use isValidating
in two separate API calls inside of one component?
I have a dashboard component that shows open and completed orders. I have to call two different endpoints (one for getting the open orders and one for getting the completed orders). I would like to use isValidating
to check the state of both API responses and show a loading animation accordingly.
//Order Dashboard Component
import Callout from '../components/cards/Callout';
function OrdersDashboard() {
const ordersEndpoint = `${BASE_URL}/orders`;
const openOrdersEndpoint = `${ordersEndpoint}&completed=false`;
const completedOrdersEndpoint = `${orderEndpoint}&completed=true`;
//Endpoint #1
const {
data: openOrders,
error: openOrdersError,
isValidating,
} = useSWR([openOrdersEndpoint, BASE_URL], ([url, audience]) =>
fetchData(url, audience)
);
//Endpoint #2
const {
data: completedOrders,
error: completedOrdersError,
isValidating,
} = useSWR([completedOrdersEndpoint, BASE_URL], ([url, audience]) =>
fetchData(url, audience)
);
if (completedOrdersError || openOrdersError) {
return <div>Error</div>;
}
if (!completedOrders && !openOrders) {
return <div>Loading...</div>;
}
return (
<>
<h1>Orders Dashboard</h1>
<section id='openOrders' className='section'>
{!openOrders || !openOrders.length ? (
<>
<h2>Open Orders</h2>
<Callout
message='No Open Orders'
isValidating={isValidating}
/>
</>
) : (
<DataTable columns={columns} data={openOrders} />
)}
</section>
<section id='completedOrders' className='section'>
{!completedOrders || !completedOrders.length ? (
<>
<h2>Completed Orders </h2>
<Callout
message='No Completed Orders'
isValidating={isValidating}
/>
</>
) : (
<DataTable columns={columns} data={completedOrders} />
)}
</section>
</>
);
}
Solution:
//Endpoint #1
const {
data: openOrders,
error: openOrdersError,
isValidating: validatePending
} = useSWR([openOrdersEndpoint, BASE_URL], ([url, audience]) =>
fetchData(url, audience)
);
//Endpoint #2
const {
data: completedOrders,
error: completedOrdersError,
isValidating: validateCompleted
} = useSWR([completedOrdersEndpoint, BASE_URL], ([url, audience]) =>
fetchData(url, audience)
);