Home > other >  quiz.map is not iterable - React
quiz.map is not iterable - React

Time:02-19

Im making a self-project - a quiz app.

It gets random strings from an api which generates a random object of 5 questions, including correct answers and wrong answers and the like .

function App() {
  const [quiz, setQuiz] = React.useState({});
  const [resetGame, setNewGame] = React.useState(false);
  const [showStartMenu, setStartMenu] = React.useState(true);

  const toggleMenu = () => {
    setStartMenu(!showStartMenu)
  }

  function getQuizDetails(){
  fetch(`https://opentdb.com/api.php?amount=5&category=9`)
    .then(res => res.json())
    .then(data => setQuiz(data["results"]))
  }

  React.useEffect(() => {
    getQuizDetails();
  }, [resetGame])

  //const quizJson = JSON.stringify(quiz, null, 0);
  const questions = quiz.map(x => x);



  return (
    <main>

      {!showStartMenu && <button onClick={toggleMenu}>Main Menu (For debug purposes only) </button>}
      {showStartMenu && <Start toggleMenu={toggleMenu} />}
      {!showStartMenu && <pre>{JSON.stringify(questions, null, 2)}</pre>}

    </main>
  );
}

export default App;

But for some reason, when I try to map over the object, it doesnt work , rather it returns an error

 Uncaught TypeError: quiz.map is not a function
    at App (App.jsx:26:26)

Any way to approach this issue ? I'd like help rather than som1 pointing to some article or the like.

Note:- It works fine when I dont map or do anything and just refer to the quiz state. But I need to find a way to access the stuff like question, answer and stuff, so yea.

Here is the repl.it link if you need to see full source code. Quiz App - Replit

I typed this in a hurry so feel free to ask what I should elaborate on .

I found something interesting

When I do

  const questions = quiz.map(x => x);

map it seems to work.

However when I try

  const questions = quiz.map(x => {
    return <Quiz questions={x["question"]} />
  });

It returns the error.

CodePudding user response:

Because you set quiz initial state as Object: {}, instead set it as Array: []

From

const [quiz, setQuiz] = React.useState({});

To

const [quiz, setQuiz] = React.useState([]);

CodePudding user response:

.map() is for arrays. But quiz is not an array, it's an empty object:

const [quiz, setQuiz] = React.useState({});

You may later set it to an array after fetching data. But its initial state is an object. If you instead want that state to be an array, make it an array:

const [quiz, setQuiz] = React.useState([]);
  • Related