I’m using JavaScript Fetch to access an API and I want to show a loader while the fetch is in progress. I’m using the following code…
async function fetchStates() {
showLoader();
await fetch('https://localhost:7123/locations/states?token=@{@HttpContext.Session.GetString("sessionToken")}')
.then(response => response.json())
.then(states => {
for (let i = 0;i < states.length;i++){
let option = document.createElement('option');
option.text = states[i].name;
option.value = states[i].id;
ddlCAStates.appendChild(option)
}
/*hideLoader(1);
scrollToTop(1);*/
})
.catch(error => {
divErrors.style.display = "block";
let errorName = GetHttpErrorName(error.toString());
txtErrors.textContent = 'The server responded with error: ' + error + ' ' + errorName;
/*hideLoader(2);
scrollToTop(2);*/
})
.finally(() => {
hideLoader();
scrollToTop();
});
}
function showLoader() {
document.getElementById('loader').style.display = 'block';
}
function hideLoader() {
document.getElementById('loader').style.display = 'none';
}
function scrollToTop() {
document.body.scrollTop = 0; // For Safari
document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera
}
The loader displays for a split second and then hides way before the fetch is completed. The loader should be visible until either the fetch successfully loads data or it fails for any reason. What I’m doing wrong here?