I've been trying to access the values inside an array of objects but for some reason when I use console.log(quiz.questions[0].question) I get the error
TypeError: Cannot read property 'question' of undefined
code:
const quizAPI = process.env.REACT_APP_API_QUIZ;
const PlayQuiz = () => {
const [quiz, setQuiz] = useState({
title: '',
questions: {},
});
useEffect(() => {
async function getQuiz() {
const param = window.location.search;
const id = param.split('=');
const Quiz = await axios.get(`${quizAPI}?_id=${id[1]}`);
const { doc } = Quiz.data.data;
console.log(doc[0]);
const quizDoc = doc[0];
setQuiz({ ...quiz, title: quizDoc.title, questions: quizDoc.questions });
}
getQuiz();
}, []);
console.log(quiz.questions[0].question);
what console.log(quiz) shows:
{title: "findme", questions: Array(3)}
questions: Array(3)
0: {_id: "5f5500caab44c4bd2b58b109", question: "sfdf", answerSelectionOne: "sdvsv", answerSelectionTwo: "asd", answerSelectionThree: "", …}
1: {_id: "5f5500cdab44c4bd2b58b10a", question: "sfdfddd", answerSelectionOne: "sdvsv", answerSelectionTwo: "asd", answerSelectionThree: "", …}
2: {_id: "5f5500cfab44c4bd2b58b10b", question: "sfdfdddv", answerSelectionOne: "sdvsv", answerSelectionTwo: "asd", answerSelectionThree: "", …}
length: 3
__proto__: Array(0)
title: "findme"
__proto__: Object