0

Here is my code for App component.

import { nanoid } from "nanoid";
import { useEffect, useState } from "react";
import Quiz from "./Components/Quiz";
import axios from "axios";

export default function App() {

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

  useEffect(() => {
    const newQuiz = [];
    axios.get("https://opentdb.com/api.php?amount=5").then((data) =>
      data.data.results.map((val) =>
        newQuiz.push({
          id: nanoid(),
          question: val.question,
          correctAns: val.correct_answer,
          options: [...val.incorrect_answers, val.correct_answer],
        })
      )
    );
    setQuiz(newQuiz);
  }, []);

  console.log(quiz)
  const quizElements = quiz.map((val) => <Quiz key={val.id} value={val} />);

  return <div>{quizElements}</div>;
}

console.log(quiz) // quiz is printed there in console.

Here is the code for Quiz component.

export default function Quiz(props) {
  return (
    <div>
      <h3>{props.value.question}</h3>
    </div>
  );
}

But In html, It's totally blank. What is the problem here?

  • 1
    You're never setting the data. You use `map` and return that array from your `then` callback, but nothing ever uses the fulfillment value of the promise that `then` produces. Instead, move your `setQuiz` call *into* the `then` callback, passing in the result of the `map`. – T.J. Crowder Mar 28 '22 at 07:53
  • Don't do `newQuiz.push`. You're not waiting for the data – evolutionxbox Mar 28 '22 at 07:57

0 Answers0