diff --git a/src/App.jsx b/src/App.jsx index b7bde75..467e678 100644 --- a/src/App.jsx +++ b/src/App.jsx @@ -1,19 +1,44 @@ -import { useState } from "react"; +import { useState, useEffect } from "react"; import ResultCard from "./components/ResultCard"; import QuestionCard from "./components/QuestionCard"; import { shuffleArray } from "./lib/utils"; -import rawTriviaQuestion from "./lib/data"; - -const triviaQuestion = rawTriviaQuestion.results[0]; function App() { const [selectedAnswer, setSelectedAnswer] = useState(null); - const [questionData, setQuestionData] = useState(triviaQuestion); + const [questionData, setQuestionData] = useState(null); + const [loading, setLoading] = useState(true); + + // Function to fetch a new trivia question + const fetchNewQuestion = async () => { + setLoading(true); + try { + const response = await fetch("https://opentdb.com/api.php?amount=1&category=9&type=multiple"); + const data = await response.json(); + if (data.results && data.results.length > 0) { + setQuestionData(data.results[0]); + } else { + console.error("No questions found."); + } + } catch (error) { + console.error("Error fetching question:", error); + } finally { + setLoading(false); + } + }; + + useEffect(() => { + fetchNewQuestion(); // Fetch the first question when the component mounts + }, []); const selectAnswer = (selection) => { setSelectedAnswer(selection); }; + const loadNewQuestion = () => { + setSelectedAnswer(null); // Reset selected answer + fetchNewQuestion(); // Fetch a new question + }; + let card; if (selectedAnswer) { @@ -23,7 +48,9 @@ function App() { answer={questionData.correct_answer} /> ); - } else { + } else if (loading) { + card =
Loading question...
; + } else if (questionData) { let options = [ questionData.correct_answer, ...questionData.incorrect_answers, @@ -41,7 +68,9 @@ function App() {