Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show loading icon till await finishes

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 ?

like image 693
Yasar Abdullah Avatar asked Nov 12 '19 14:11

Yasar Abdullah


1 Answers

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>
like image 61
lankovova Avatar answered Oct 07 '22 01:10

lankovova