I can console.log (inside the method) the 'newQuestion' object/'answers' array with no issue but when running the app I am met with the "cannot read properties of undefined" error. The weirdest part is that it actually displays the information on the page (it works I guess?) but the error isn't going away for some reason.
Template html code
<h2>Questions</h2>
<div class="quiz" :key="currentQuestionIndex">
<h2>{{ questions[currentQuestionIndex].text }}</h2>
<div class="answers-container">
<div
class="answer answer--option"
v-for="(answer, index) in questions[currentQuestionIndex].answers"
@click="selectAnswer(index)"
:class="{
'is-selected': chosenAnswers[currentQuestionIndex] == index,
}"
:key="index"
>
{{ answer.text }}
</div>
</div>
generateQuestions() method code:
generateQuestions(response) {
if (response.length > 0) {
response.forEach((questionData) => {
const newQuestion = {}; // Question object
const answers = []; // Answers array
[
...questionData.incorrect_answers, //Establish params from api
questionData.correct_answer,
].forEach((answer) => {
let answerObject = { text: "", correct: false }; // Two properties to each answer
[answerObject.text, answerObject.correct] = [
answer,
answer == questionData.correct_answer, // Assign correct answer
];
answers.push(answerObject);
});
newQuestion.text = questionData.question;
newQuestion.answers = answers;
this.questions.push(newQuestion); // Push newQuestion object to questions array in data
});
} else {
alert("something went wrong");
}
I have been console.logging every step of the process to find any discrepancies but none where found. I should mention it isn't just returning this error for the 'text' property. It also happens for 'answers' etc. I can add more code if needed or relevant to solving issue.
questions[currentQuestionIndex]?.text
in the h2answerObject
, followed by a line where you use array-destructuring to assign values to the propertiestext
andcorrect
is rather strange. Why don't you assign the values when the binding is established:let answerObject = { text: answer, correct: answer === questionData.correct_answer }
? Or just reduce that whole block into:answers.push({ text: answer, correct: answer === questionData.correct_answer });