Ask Your Question
3

How to display a preloader element while waiting for server response using FETCH?

asked 2023-06-22 12:52:59 +0000

scrum gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-06-22 13:02:01 +0000

lalupa gravatar image

You can display a preloader element while waiting for a server response using fetch by following these steps:

  1. Create a variable that references the element to be displayed as the preloader.

    const preloader = document.querySelector('.preloader');
    
  2. Before making the fetch request, display the preloader element.

    preloader.style.display = 'block';
    
  3. Make the fetch request as you would normally.

    fetch('/api/data')
     .then(response => response.json())
     .then(data => {
       // handle the data returned
     })
     .catch(error => {
       // handle any errors
     });
    
  4. After the request is complete, hide the preloader element.

    preloader.style.display = 'none';
    

Here's the complete example:

const preloader = document.querySelector('.preloader');

preloader.style.display = 'block';

fetch('/api/data')
  .then(response => response.json())
  .then(data => {
    // handle the data returned

    preloader.style.display = 'none';
  })
  .catch(error => {
    // handle any errors

    preloader.style.display = 'none';
  });
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-22 12:52:59 +0000

Seen: 17 times

Last updated: Jun 22 '23