Home > Enterprise >  React problem Cannot read properties of undefined (reading 'map') in a quiz app?
React problem Cannot read properties of undefined (reading 'map') in a quiz app?

Time:05-21

I am working on a quiz project. Particularly I am working on selecting an answer out of 4 options. Whenever I click on an option I am encountering an error which is given below enter image description here

This is my App.js file

import { useEffect, useState } from "react";
import Quiz from "./components/Quiz";
import { nanoid } from "nanoid";
function App() {
  const [showScreen, setShowScreen] = useState(false);
  const [quizData, setQuizData] = useState([]);

  useEffect(() => {
    fetch("https://opentdb.com/api.php?amount=5&category=21&type=multiple")
      .then((res) => res.json())
      .then((data) =>
        setQuizData(
          data.results.map((question) => {
            return {
              ...question,
              id: nanoid(),
              answers: shuffle([
                ...question.incorrect_answers,
                question.correct_answer,
              ]),
              correct_answer: question.correct_answer,
            };
          })
        )
      );
  }, []);

  function shuffle(arr) {
    let array = arr.map((ans) => {
      return {
        id: nanoid(),
        answer: ans,
        isSelected: false,
      };
    });
    for (let i = array.length - 1; i > 0; i--) {
      let j = Math.floor(Math.random() * (i   1));
      let temp = array[i];
      array[i] = array[j];
      array[j] = temp;
    }
    return array;
  }

  function handleSelect(id, selectedAnsId) {
    console.log(id, selectedAnsId);
    setQuizData((prevQuizData) => {
      console.log(quizData);
      prevQuizData.map((question) => {
        return question.id === id
          ? {
              ...question,
              answers: question.answers.map((answer) => {
                return answer.id === selectedAnsId
                  ? {
                      ...answer,
                      isSelected: !answer.isSelected,
                    }
                  : { ...answer, isSelected: false };
              }),
            }
          : question;
      });
    });
  }

  const newQuizData = quizData.map((question) => {
    return (
      <Quiz
        key={question.id}
        id={question.id}
        question={question.question}
        answers={question.answers}
        handleSelect={handleSelect}
      />
    );
  });

  function openSeparateScreen() {
    setShowScreen((prevShowScreen) => !prevShowScreen);
  }
  return (
    <div className="App">
      {showScreen ? (
        <div className="quiz-container">
          {newQuizData}

          <button
            style={{
              display: "flex",
              justifyContent: "center",
              alignItems: "center",
              margin: "auto",
            }}
            className="btn"
          >
            Check answers
          </button>
        </div>
      ) : (
        <div className="container">
          <h1 className="heading">Quizzical</h1>
          <p className="text">To start a quiz please click on the button</p>
          <button className="btn" onClick={openSeparateScreen}>
            Start Quiz
          </button>
        </div>
      )}
    </div>
  );
}

export default App;

This is my Quiz.js file

import React from "react";

const Quiz = (props) => {
  return (
    <>
      <div className="questions">
        <h3>{props.question}</h3>
        <div className="options">
          {props.answers.map((answer) => {
            return (
              <h6
                key={answer.id}
                className={`${
                  answer.isSelected ? "isSelected" : "transparent"
                }`}
                onClick={() => props.handleSelect(props.id, answer.id)}
              >
                {answer.answer}{" "}
              </h6>
            );
          })}
        </div>
      </div>
      <hr />
    </>
  );
};

export default Quiz;

The error message shows I am getting the error at line 66 which starts from

const newQuizData = quizData.map((question) => {
        return (
          <Quiz
            key={question.id}
            id={question.id}
            question={question.question}
            answers={question.answers}
            handleSelect={handleSelect}
          />
        );
      });

any kind of help would be much appreciated.

CodePudding user response:

Your quizData is undefined at some point.

The most likely culprit is


setQuizData((prevQuizData) => {
      console.log(quizData);
      prevQuizData.map((question) => {
  • you don't return the value there; try to change it to return prevQuizData.map((question) => {
  • Related