Home > Net >  Uncaught TypeError: Cannot read properties of undefined (reading 'questionText')
Uncaught TypeError: Cannot read properties of undefined (reading 'questionText')

Time:07-19

I get an error message that my "questionText" could not be read or is not defined. The first code is where I use "questionText" and the second code is where I want to drag it. Did I do something wrong that he can't read "questionText"? If you need anything else just write. I need to take away some of the code because StackOverflow doesn't want that much code :( .

import React from 'react'
import Card from './Card'

import "./Question.css"

const Question = ({
  questionIndex,
  setQuestionIndex,
  questions,
  setShowQuestionsPagePop,
  setShowFinalPage,
  score,
  setScore,
}) => {
  const handleClick = (isCorrect) => {
    if (questionIndex < 9) {
      if (isCorrect) {
        setScore((score) => score  = 100);
      }

      setQuestionIndex((prevIndex) => prevIndex   1);
    } else {
      if (isCorrect) {
        setScore((score) => (score  = 100));
      }

      setShowQuestionsPagePop(false);
      setShowFinalPage(true);
    }
  };


  return (
    <Card>
      <h1 className="question">{questions[questionIndex].questionText}</h1>

      <div className="answers">
        {questions[questionIndex].answers.map((answer, index) => (
          <div 
            className="answer"
            key={index}
            onClick={() => handleClick(answer.correctAnswer)}
          >
            <p>{answer.answerText}</p>
          </div>
        ))}
      </div>
    </Card>
  )
}

export default Question
export const questions = [
    {
      questionText: "How long is an Olympic swimming pool (in meters)",
      answers: [
        {
          answerText: "50",
          correctAnswer: true,
        },
        {
          answerText: "60",
          correctAnswer: false,
        },
        {
          answerText: "75",
          correctAnswer: false,
        },
        {
          answerText: "100",
          correctAnswer: false,
        },
      ],
    },
  ];

CodePudding user response:

You can use the optional chaining, this enables you to read a property of an object if it's present, otherwise will return undefined so your code will not break, try something like:

<h1 className="question">{questions[questionIndex]?.questionText}</h1>

Another option is to manually check if the property is present and has a value so you could do something like:

<h1 className="question">{questions && questions[questionIndex] && question[index].questionText && questions[questionIndex].questionText}</h1>

but it's a very messy code so I would use the first one.

  • Related