Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add a spinner in Javascript while fetch async is loading my data? [duplicate]

Tags:

javascript

Good morning, I have a fetch async function in my js file for call ajax members into a goverment table. I want to add a spinner while the data is been loading and also I want to hide the table titles and the dropdown menu as well as checkboxes while the spinner (ajax) is working. I´m not using any framework, just js vanilla. I´m a student and I can´t use jquery for this. I have the spinner but it doesn´t disapear when the data appears on the table. Thank you so much!

async function getData(chamber) {
  members = await fetch(`https://api.propublica.org/congress/v1/113/${chamber}/members.json`, {
      method: "GET",
      headers: new Headers({
        'X-API-Key': 'iv8LMc9T9sQKOc0EfDC1NLtQU68pFsF6O6W3NPJz'
      })
    })

    .then(response => response.json())
    .then(data => data.results[0].members)
    .catch(err => console.log(err))
  webLogic(chamber);
  document.getElementsById("loader").style.display = "none"
}
like image 885
Nikita99 Avatar asked Sep 02 '25 06:09

Nikita99


1 Answers

You can achieve this by setting innerHTML of your element - note that the setTimeout is just used to "mock" your async request here. Of course you'd need something like

.then((resolvedData) => document.getElementById('myDiv').innerHTML = resolvedData)

here the snippet:

document.getElementById('load').addEventListener('click', function () {
  document.getElementById('content').innerHTML = '...'
  setTimeout(function () {
    document.getElementById('content').innerHTML = 'content loaded!'
  }, 2000)
})
<div id="content"></div>
<button id="load">load</button>
like image 178
messerbill Avatar answered Sep 04 '25 19:09

messerbill