title: How to show and hide loader while using fetch in JavaScript?
body: <p>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...</p>
  <pre><code>      async function fetchStates() {
              showLoader();
              await fetch('https://localhost:7123/locations/states?token=@{@HttpContext.Session.GetString(&quot;sessionToken&quot;)}')
              .then(response =&gt; response.json())
              .then(states =&gt; {
                  for (let i = 0;i &lt; 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 =&gt; {
                  divErrors.style.display = &quot;block&quot;;
                  let errorName = GetHttpErrorName(error.toString());
      
                  txtErrors.textContent = 'The server responded with error: ' + error + ' ' + errorName;
                  /*hideLoader(2);
                  scrollToTop(2);*/
              })
              .finally(() =&gt; {
                  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
      }
  </code></pre>
  <p>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?</p>