I'm trying to read a JSON file and trying to pass it on to the component however I am getting this error, TypeError: Cannot read property 'map' of undefined and I cant seem to find what the issue is.
here is the code i have created:
export default function Questions() {
const [currentQuestion, setCurrentQuestion] = useState(0);
const [showScore, setShowScore] = useState(false);
const [score, setScore] = useState(0);
const quizQuestions = quiz.questions;
const handleAnswerOptionClick = (isCorrect) => {
if (isCorrect) {
setScore(score + 1);
}
const nextQuestion = currentQuestion + 1;
if (nextQuestion < quizQuestions.length) {
setCurrentQuestion(nextQuestion);
} else {
setShowScore(true);
}
};
quizQuestions.map((quizQuestions)=> {
return (
<div className='questions'>
<div className="questions_row">
{showScore ? (
<div className='score-section'>
You scored {score} out of {quizQuestions.length}
</div>
) : (
<>
<QuestionsProduct
title="Introduction to Programming2"
questioNum={currentQuestion + 1}
question={quizQuestions[currentQuestion].quizQuestions.questionText}
answers={quizQuestions[currentQuestion].quizQuestions.answerOptions.map((answerOption) => (
<label onClick={() => handleAnswerOptionClick(quizQuestions.answerOption.isCorrect)}
type="checkbox">{answerOption.quizQuestions.answerText}</label>
))}
/>
</>
)}
</div>
</div>);
})
}
and the json file name is quiz.json. I currenntly have this data internaly however i want to create more questions therefore json file will be ideal. here is the json file created
[{ "questions" : {
"questionText": "What is the capital of France?",
"answerOptions": [
{ "answerText": "New York", "isCorrect": false },
{ "answerText": "London", "isCorrect": false },
{ "answerText": "Paris", "isCorrect": true },
{ "answerText": "Dublin", "isCorrect": false }
]
},
"questionText2": "What is the capital of France 2?",
"answerOptions": [
{ "answerText": "New York", "isCorrect": false },
{ "answerText": "London", "isCorrect": false },
{ "answerText": "Paris", "isCorrect": true },
{ "answerText": "Dublin", "isCorrect": false }
]
}
]