0

I am developing a Quiz application using React / Typescript for the purpose of study.

I have the state called Quiz, it consists of:

interface QuestionData {
  id: number;
  question: string;
  explanation: string;
  options: OptionsData;
}

I would like to display only the first element of the array on the screen, I know that the way to do this would be:

<p>{quiz[0].question}</p>

But, in this way, I am getting the following error:

TypeError: Cannot read property 'question' of undefined

If I print using console.log (quiz[0].question), I get the desired return. Is there any other way? Or the form I thought was correct isn't it?

Full code below:

interface VideoInfo {
  video_id: number;
}

type OptionsData = any[];

interface QuestionData {
  id: number;
  question: string;
  explanation: string;
  options: OptionsData;
}

const Quiz: React.FC<VideoInfo> = video_id => {
  const [quiz, setQuiz] = useState<QuestionData[]>([]);

  const video = video_id;

  const getQuiz = useCallback(async () => {
    try {
      await api.get(`/quiz/video/${video}`).then(response => {
        setQuiz(response.data);
      });
    } catch (err) {
      alert('error');
    }
  }, [video]);

  useEffect(() => {
    getQuiz();
  }, [getQuiz]);

  return (
    <Container>
      <ol>
        <li>
          <div className="question">
            {/* The error happens here: */}
            <p>{quiz[0].question}</p>
            <div>
              <Button type="button">A</Button>
              <Button type="button">B</Button>
              <Button type="button">C</Button>
              <Button type="button">D</Button>
            </div>
          </div>
        </li>
      </ol>
    </Container>
  );
};

export default Quiz;

3 Answers 3

3

In time when you try to get access to quiz[0] this element does not exists yet. Try to do something like that:

{quiz && quiz[0].question}

OR

{quiz[0]?.question}

That way you check if element exists before you try to get access to it.

Sign up to request clarification or add additional context in comments.

Comments

1

try this

        <p>{quiz[0]?.question}</p>

Comments

0

If you want just the first, you can take it from the array this way:

const [first] = response.data;

You can get other indexes to:

const [first, second] = response.data;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.