Does Axios take long to consume the API?

Asked

Viewed 129 times

-1

Hey, guys! All right?

I am starting my studies in Vanilla Javascript to study future frameworks using js.

I made a small web project in which the user type the ZIP code of the residence and the application uses Axios to consume an api that returns the data of the zip (neighborhood, street, city...)

However, I noticed that at the first click on the search button, the return is "Undefined" and, after clicking again, the correct result is shown on the screen. I think it may be a "delay" for the return of data.

Just follow my code:

(Note: Model MVC)

ZIP Class:

 class Cep {

   constructor(){

        this.cidade;
        this.bairro;
        this.rua;
   }

   getRua(){

        return this.rua;
   }

   getBairro(){

        return this.bairro;
   }

   getCidade(){

        return this.cidade;
   }


   setEndereco(cidade,bairro,rua){

    this.cidade = cidade;
    this.bairro = bairro;
    this.rua = rua;
   }

}

VIEW class (renders html on screen)

class View{

constructor(dom){

    this.dom = dom;
}


template(modelo){

    return `
    <table class="table table-hover table-bordered mt-5">
    <thead>
        <tr>
            <th>Cidade</th>
            <th>Bairro</th>
            <th>Rua</th>
        </tr>
    </thead>

    <tbody>


        <tr>
            <td>${modelo.getCidade()}</td>
            <td>${modelo.getBairro()}</td>
            <td>${modelo.getRua()}</td>               
        </tr>


    </tbody>
    `
}

update(modelo){

    this.dom.innerHTML = this.template(modelo);
}

}

Finally, the Controller class

 class CepController{

    constructor(){

        this.dom = document.querySelector('#cep');
        this.tabela = document.querySelector('#enderecos');
        this.url = 'http://api.postmon.com.br/v1/cep/';
        this.objCep = new Cep();
        this.view = new View(this.tabela);
    }

    render(){

        axios.get(this.api_url(this.dom.value)).then((resposta)=>{

            this.objCep.setEndereco(resposta.data.cidade,resposta.data.bairro,resposta.data.logradouro);
        });       

        console.log(this.objCep);

        this.view.update(this.objCep);

        console.log(this.objCep);


        event.preventDefault();
    }

    api_url(cep){

        let retorno = this.url + cep;
        return retorno;
    }


}

NOTE: I apologize if my doubt is too trivial. I searched a lot and really did not find answers to my problem :(

1 answer

3

You are not waiting for the reply of the request to arrive before trying to show the data. Try so:

axios.get(this.api_url(this.dom.value)).then((resposta)=>{ 
    this.objCep.setEndereco(resposta.data.cidade, resposta.data.bairro, resposta.data.logradouro)
    this.view.update(this.objCep);
}); 

Browser other questions tagged

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