简体   繁体   中英

React.js - Unable to access values inside array of objects

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

Usually this means you are trying to access a property on a possibly null or undefined variable.

Probably you need to change the initial useState first because questions is an array and not an object {} as the following:

const [quiz, setQuiz] = useState({
    title: '',
    questions: [],
});

Secondly quiz.questions can have length of 0 . So with a simple check before like quiz.questions.length > 0 you can eliminate that issue.

Then you can use logging as:

console.log(quiz.questions.length > 0 ? quiz.questions[0].question : null);

In order to access the quiz field values correctly it is recommended to use another useEffect that watches the quiz state :

    useEffect(() => {
        
        if(quiz.questions.length){
           console.log(quiz.questions[0].question);
         }
        
    }, [quiz]);

it seems like you are trying to use an object {} as an array []!

What Javascript is trying to do is access this:

{
 "0" : { // your data},
}

What it should look like:

[
 0 : { // your data},
]

What you want to change is :

const [quiz, setQuiz] = useState({
    title: '',
    questions: [], // make it an array
});

And possibly consider using .push() to push individual objects to an array

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM