From 874988ecc9a2f250ba4d9f0a543ee81a1fc7cfcc Mon Sep 17 00:00:00 2001 From: Ljupcho-Atanasov Date: Fri, 27 Sep 2024 13:17:14 -0400 Subject: [PATCH] Completed Trivia_Lab --- package-lock.json | 4 ++-- src/App.jsx | 47 ++++++++++++++++++++++++++++++++++------------- 2 files changed, 36 insertions(+), 15 deletions(-) diff --git a/package-lock.json b/package-lock.json index 254efeb..bd79634 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "lab-react-trivia-solution", - "version": "0.0.0", + "version": "0.2.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "lab-react-trivia-solution", - "version": "0.0.0", + "version": "0.2.0", "dependencies": { "react": "^18.3.1", "react-dom": "^18.3.1" diff --git a/src/App.jsx b/src/App.jsx index b7bde75..94f7aa4 100644 --- a/src/App.jsx +++ b/src/App.jsx @@ -1,22 +1,41 @@ -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]; - + +// API URL to fetch a new question +const API_URL = "https://opentdb.com/api.php?amount=1&category=9&type=multiple"; + function App() { const [selectedAnswer, setSelectedAnswer] = useState(null); - const [questionData, setQuestionData] = useState(triviaQuestion); - + const [questionData, setQuestionData] = useState(null); + + // Function to fetch a new question from the API + const fetchNewQuestion = + async () => { + const response = await fetch(API_URL); + const data = await response.json(); + setQuestionData(data.results[0]); // ??????? Set the new question data ????????????????????????? + setSelectedAnswer(null); // Reset selected answer + }; + + // Use useEffect to fetch the initial question when the component mounts + useEffect(() => { + fetchNewQuestion(); + }, []); + const selectAnswer = (selection) => { setSelectedAnswer(selection); }; - + let card; - - if (selectedAnswer) { + + if (!questionData) { + // Render loading state if questionData is null + card =
Loading...
; + } else if (selectedAnswer) { + // Render ResultCard if an answer is selected card = ( ); } else { + // Shuffle options and render QuestionCard if no answer is selected let options = [ questionData.correct_answer, ...questionData.incorrect_answers, @@ -36,16 +56,17 @@ function App() { /> ); } - + return (

Trivia App

- + {card}
); } - -export default App; +export default App; \ No newline at end of file