-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 :(