1
I’m doing a project with Vuejs and I have these two functions running through an array provided by a JSON fetch.
import { api, getCep } from "@/services.js";
export default {
name: 'Casos',
data() {
return {
//cep: '',
//bairro: '',
bairros: '',
casoPorBairro: '',
casos: null,
valores: '',
totalCasos: '',
totalObitos: '',
changeView: false,
listBairros: [],
searchBairro: '',
searchCasos: '',
searchObitos: '',
};
},
methods: {
buscarCep() {
const cep = this.cep.replace(/\D/g, "");
if(cep.length === 8) {
getCep(cep).then(r => {
this.bairro = r.data.bairro;
})
}
},
getCasos() {
api.get(`/covid19.min.json`).then(r => {
this.casos = r.data.bairros; // => PRODUCTION
//this.casos = r.data; // => DEVELOPMENT
});
},
showBairro() {
for(let i = 0; i < this.casos.length; i++){
this.listBairros.push(this.casos[i]);
}
const result = this.listBairros.find(list => list.bairro === this.bairros);
if(result) {
this.searchBairro = result.bairro;
this.searchCasos = result.casos;
this.searchObitos = result.obitos
}
},
getValorMax() {
let sumCasos = 0;
let sumObitos = 0;
for(let i = 0; i < this.casos.length; i++){
this.valores = this.casos[i].casos;
sumCasos = sumCasos + this.casos[i].casos;
sumObitos = sumObitos + this.casos[i].obitos;
}
this.totalCasos = sumCasos.toLocaleString();
this.totalObitos = sumObitos.toLocaleString();
},
changeColor() {
const btnList = document.querySelector('button[data-btn="list"]');
const btnTable = document.querySelector('button[data-btn="table"]');
if(this.changeView === false) {
btnList.classList.remove('active');
btnTable.classList.add('active');
} else {
btnList.classList.add('active');
btnTable.classList.remove('active');
}
}
},
created() {
this.getCasos();
},
beforeUpdate() {
this.getValorMax();
this.getCasos();
this.showBairro();
},
updated() {
this.changeColor();
}
}
As I need to wait for my fetch to occur to insert the json data into the array, both functions are being called in the method beforeUpdate()
of the Vue.
However, the for loop of both functions are generating an infinite loop.
Follows full file: https://github.com/GuiiHenriq/sp-covid19/blob/master/src/components/Casos.vue
How can I fix this?
Clarifies 2 things: 1) why you call
this.getCasos();
in beforeUpdate and not only 1 time when the component loads? 2) the data source over which everything else is calculated comes from thatthis.getCasos();
right?– Sergio
Sergio, your comment helped me clarify the problem, really the infinite loop is being caused because getCasos() was being called in beforeUpdate too, the correct is to call only when creating the component.
– GuiHenriq
If you answer my questions you have a one-answer bonus telling you how you can do it in a better way ;)
– Sergio
this.getCasos()
in the methodcreated()
. 2) That exact, thethis.getCasos()
is where I have my Axios get function. The two other functionsthis.showBairro()
andthis.getValorMax()
are using thethis.getCasos()
.– GuiHenriq