Array.map is not iterable - React

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 .

Code
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 .

Edit :
I found something interesting

When I do

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

it seems to work.

However when I try

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

It returns the error.

Does this have anything to do with the Quiz component?

Isn’t the quiz initially an object and gets replaced with array only after fetch?

Yes. I fetch the json object from https://opentdb.com/api.php?amount=5&category=9 .

Then why you initialize quiz to an empty object?

Oh …

Thats so true. Thanks ! It works now.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.