I'm struggling to comprehend why my array is showing as undefined in my Vue component. The issue arises in the following scenario:
- The SelectCategories.vue component uses the router to navigate to the Quiz.vue component. Here, I utilize props to transmit data to the Quiz component. This is how it's executed:
else {
this.$router.push({
name: 'quiz',
params: {
items: selectedCategories
}
})
}
We move forward to the Quiz.vue component, where I execute the following within the created lifecycle 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 connects with the database and retrieves certain information, which is then added to the questions array that I have defined here:
export default {
name: 'quiz',
props: ['items'],
data: function() {
return {
questions: [],
error: '',
};
}
Ultimately, I attempt to access this data in the template via an h1 tag:
<h1>{{questions[0][0].description}}</h1>
Unfortunately, I encounter the subsequent error:
TypeError: Cannot read property '0' of undefined
In the console, what I observe is:
{{questions[0][0].description}}
This is occurring prior to populating the questions array in the created lifecycle hook. Referencing this screenshot https://i.sstatic.net/7ItKW.png.
My understanding is that created() is invoked before the template rendering, but there might be a misconception on my end. My goal is to ensure that the operations in created() are completed before the template loads, ensuring the array is populated beforehand. Your assistance is greatly appreciated.