Reputation: 155
I have trouble making a function asynchronous that takes data from firebase:
When component gets created I have:
created(){
this.$store.dispatch("fetchSections");
}
Vuex action:
actions: {
async fetchSections({ commit }) {
var sectionsRef = db.collection("sections");
try {
await sectionsRef.get().then((querySnapshot) => {
var collect = querySnapshot.docs.map((doc) => doc.data());
commit("addToSections", collect);
});
} catch (error) {
console.log(error.message + " -- " + error.statusText);
}
},
}
Problem: another component gets created before we fetch the data.
I also tried this:
actions: {
async fetchSections({ commit }) {
var sectionsRef = db.collection("sections");
try {
let allSections = await sectionsRef.get();
for (const doc of allSections.docs) {
var collect = doc.data();
commit("addToSections", collect);
}
} catch (error) {
console.log(error.message + " -- " + error.statusText);
}
},
},
Upvotes: 2
Views: 993
Reputation: 63059
The component's created
hook doesn't allow delaying rendering, only to provide some code to run at that moment in the component lifecycle.
When using the hook to make an async call for data, you can use v-if
to prevent errors on child elements that rely on that data:
<div v-if="someData && someData.length">
<div v-for="item in someData" :key="item.id">
{{ item }}
</div>
</div>
<div v-else>
Loading...
</div>
Without the v-if
, the v-for
would try to access someData
that might not exist yet, and that might throw errors when accessing properties of someData
.
Upvotes: 4