I'm having trouble understanding why an array is undefined in my Vue component. Here is the flow:
- SelectCategories.vue component uses router to push to Quiz.vue component. Here I use props to pass on data to Quiz component. Here is how it is done:
else {
this.$router.push({
name: 'quiz',
params: {
items: selectedCategories
}
})
}
We move on to Quiz.vue component, where I do the following on the created life cycle hook:
async created() {
for (const item of this.items) {
var questions = await QuestionService.getQuestionsByCategory(item);
this.questions.push(questions);
console.log(this.questions);
}
}
The QuestionService reaches out to the database and gets some information, which is pushed into the questions array I have defined here:
export default {
name: 'quiz',
props: ['items'],
data: function() {
return {
questions: [],
error: '',
};
}
Finally, I try to access this data in the template using an h1:
<h1>{{questions[0][0].description}}</h1>
However, I end up with the following error:
TypeError: Cannot read property '0' of undefined
What I am seeing in the console is that:
{{questions[0][0].description}}
Is happening before I populate the questions array in the created life cycle hook. As you can see here:
It is my understanding that created is called before the template, but I might be wrong. What I want to accomplish is to have the functionality in created() have happen before the template is loaded, so the array gets populated first. Thank you for the help.
