0
I am facing problems with Vuex and Javascript, I believe because I am not able to work well with Promises, Vuex and Async/Await
I have a function that runs through an array (map) Inside an if, I check if I don’t have this ID in my Vuex
Trouble comes in, I call the function this.getCentroDeCustos(itemArray.contaGerencial.id);
, where its function is to just make a call and save data in vuex, but the rest of my code is not waiting for its completion and ends up saving data from my empty array because in Vuex the first time I run it is still empty.
Below my code:
getCentroDeCustosCache(arrayPraPercorrer){
//Vou atrás dos centros de custos e jogo em cache
let nomeCentroDeCusto = '';
let idCentroDeCusto = '';
arrayPraPercorrer.map((itemArray, index) => {
if(this.cacheCG.idContasGerenciais.indexOf(itemArray.contaGerencial.id) == -1) {
this.getCentroDeCustos(itemArray.contaGerencial.id);
}
this.cacheCG.centroDeCustos.map(itemCG => {
if(itemCG.centroDeCusto == itemArray.centroDeCusto.replace(/\s/g,'')){
arrayPraPercorrer[index].nome = itemCG.nome
arrayPraPercorrer[index].idCentroDeCusto = itemCG.id
}
});
});
alert(JSON.stringify(arrayPraPercorrer) + 'CAIUUU ***************')
return arrayPraPercorrer;
},
This code below is the function I call that takes the new data to my vuex.
async getCentroDeCustos(idDaContaGerencial){
await axios({
method: "get",
url: `/centrosdecustos/contasgerenciais/${idDaContaGerencial}`,
responseType: "json",
headers: {
Authorization: `Basic ${btoa(this.loggedUser.email + ":")}`,
Accept: "application/json",
"Content-Type": "application/json"
}
}).then(response => {
this.$store.commit('setCC', {
itemName: 'cacheCG',
arrayName: 'centroDeCustos',
content: response.data
});
this.$store.commit('setInArray', {
itemName: 'cacheCG',
arrayName: 'idContasGerenciais',
content: idDaContaGerencial
});
})
},
You are mixing some concepts... you can clarify some doubts: which version of Vuex are you using? how is your template?
– Sergio
Vuex: 3.0.1 I changed the code structure, I commented there where the problem is going: https://codepen.io/anon/pen/dBywNz
– Andre Pazini