Reputation: 358
I'm using fetch API to access a REST API I developed and hosted online. But when retrieving data from the database (>60 rows) to be displayed in a section of the page, it takes about 3-5 seconds to display the data which I styled with HTML and CSS.
My question is how can i implement a css preloader to load before the actual data is displayed. And how do i know that the data has been displayed.
Below is a part of my code.
// Front end
frontend.html
<table>
<caption>User requests</caption>
<thead class="table-head">
<tr>
<th scope="col">Request Id</th>
<th scope="col">User ID</th>
<th scope="col">Brand</th>
<th scope="col">Type</th>
</tr>
</thead>
<tbody id="tablebody">
<div class="loader" id="loader"></div>
</tbody>
</table>
// file.js
fetch(url, {
method: 'GET',
headers: {'Authorization': 'Bearer ' +token}
}).then(response =>{
// Redirect the user to the login page
// If the user is not an admin
if(response.status === 401) {
window.location.replace('./Index.html');
}
return response.json()
})
.then((data) => {
let completedata = data.allRequests;
if(completedata) {
completedata.forEach((item) => {
timeStamp = new Date(item.createdon);
dateTime = timeStamp.toDateString();
theOutput +=`<tr id="listofrequests"><a href=""></a><td data-
label="Request Id">${item.id}</td> </a>
<td data-label="Brand">${item.userid}</td>
<td data-label="Brand">${item.brand}</td>
<td data-label="Type">${item.other}</td>
<td data-label="Status">${item.name}</td>
<td data-label="Status"><a href="./Request-status.html" class="btn
view-detail" id="${item.id}" onClick="adminviewonerequest(this.id)">view</a>
</td>
<td data-label="Cancel"><button class="danger" id="${item.id}"
name="${item.name}" onClick="return cancelrequest(this.id, this.name)"><i
class="fa fa-trash"> Cancel Request</i></button></td>
</tr>`;
});
}
else {
toastr.warning(data.message);
}
document.getElementById('tablebody').innerHTML = theOutput;
})
.catch(err => console.log(err));
Upvotes: 0
Views: 2919
Reputation: 872
Use on of those already implemented load spinners How to make a loading spinner in html
Then , In your html code add <div id="loading" class="loader"></div>
, Which make the loader displayed by default
and Using fetch :
fetch(YouUrl)
.then(res => {
if(res == 404){
// To hide the loader when the error is happen , There is no need to use loader
// Show some toaster notification for the user or sweet alert
document.getElementById("loading").style.display = 'none';
}
})
.then(json => {
// Here is your data so you need to hide the loader
document.getElementById("loading").style.display = 'none';
});
Upvotes: 3