I have a async function with await fetch. I want to show a loading icon to user till the await completes and then show the next div.
let getOTP = await fetch(url, {
method: 'POST',
headers: {
"Content-Type": "text/plain"
},
body: JSON.stringify({
"Number": mobileNumber
})
});
let data = await getOTP.json();
let errorCode = data.errorCode;
if (errorCode == 0) {// show next div}
I have tried used setTimeout(function (){},5000) functions set to 5 seconds (or more) but sometimes it takes longer for the reply to come. So, How do I show a loading icon till the await completes ?
Simply display loader before fetch, and remove it after await
.
const fetchButton = document.querySelector('#fetchButton')
const loader = document.querySelector('#loader')
const content = document.querySelector('#content')
function fetchData() {
// Here should be your api call, I`m using setTimeout here just for async example
return new Promise(resolve => setTimeout(resolve, 2000, 'my content'))
}
fetchButton.onclick = async function () {
content.innerHTML = ''
// Your loader styling, mine is just text that I display and hide
loader.style.display = 'block'
const nextContent = await fetchData()
loader.style.display = 'none'
content.innerHTML = nextContent
}
<button id="fetchButton">Fetch</button>
<div id="loader" style="display: none">Loading...</div>
<div id="content"></div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With