Load Code in JS

Asked

Viewed 142 times

-1

I wish the following loading indicator : <li Carregando...</li> appears on screen instead of a list of elements while the request is being performed. This is my code :

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UFT-8">
  <title> </title>
</head>
<body>

    <form id="form-usuario" onsubmit="searchUsuario()" method="POST">
        <input type="text" name="user" id="usuario" placeholder="Informe o usuario do github">
        <button type="submit">Buscar usuário</button>
      </form>

      <div>
    <ul id = lista>

    </ul>
      </div>

  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <script>

    //função para procurar o usuário
    function searchUsuario() {

      alert("searching...")
      event.preventDefault()

      let coleta = document.getElementById("usuario").value

      axios.get(`https://api.github.com/users/${coleta}/repos`)
        .then(function(response) {//caso o usuário seja encontrado...
          console.log(response)

          var nomes = []//vetor que armazenará os repositórios
          nomes.push(`https://api.github.com/users/${coleta}/repos`)//adiciona o usuário obtido na busca/pesquisa do usuário

          for (var i = 0; i<nomes.length; i++){
              var lis = document.createElement('li')
              lis.innerHTML = nomes[i]
              lista.appendChild(lis)
          }
          console.log(nomes)

        })
        .catch(function(error) {
          console.log(error)
          console.log("Este usuário do github não existe")
        })
    }
  </script>
</body>
</html>

How to solve this?

1 answer

1

After the event.preventDefault() place:

var carregando = document.getElementById("carregando");
if(carregando && carregando.length) carregando.outerHTML = '';
var lista = document.getElementById("lista");
var lista_html = lista.innerHTML;
lista.innerHTML = '<li id="carregando">Carregando...</li>';

The first line search for li with the message "Loading..." by id #carregando. In the second line the if checks if it exists, and if it exists, removes.

The 3rd line assigns the list to a variable (you did not do this. You were pulling the list straight, which is not very recommended). 4th line stores HTML from list to variable temporarily lista_html. And the last line inserts the message into the list.

In the then, before the for, you reinsert the HTML that was stored in the variable lista_html:

lista.innerHTML = lista_html;

This way, the "Loading..." message will be replaced by the previous HTML and the for will insert the new items.

Case enter the block catch, put there also the code that removes the message:

document.getElementById("lista").outerHTML = '';

Remarks:

  • Always finish a line with semicolon ;.
  • In the onsubmit, send the event as a function parameter: onsubmit="searchUsuario(event)".

  • And in the function put the event also: function searchUsuario(event) { (see why in this answer).

  • The only however of this logic is that the names vector empties, making the list no longer have content at each insertion.

  • Amended answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.