From b7e4495266bfa84333c65291bba2b7b454cc8938 Mon Sep 17 00:00:00 2001 From: Jack Hachicho Date: Wed, 18 Sep 2024 21:00:24 -0400 Subject: [PATCH] finished lab --- package-lock.json | 4 ++-- src/App.jsx | 37 ++++++++++++++++++++++++++++--------- 2 files changed, 30 insertions(+), 11 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..63063d3 100644 --- a/src/App.jsx +++ b/src/App.jsx @@ -1,14 +1,31 @@ -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); + + useEffect(() => { + fetchNewQuestion(); + }, []); + + const fetchNewQuestion = () => { + setLoading(true); + setSelectedAnswer(null); + fetch('https://opentdb.com/api.php?amount=1&category=9&type=multiple') + .then(response => response.json()) + .then(data => { + setQuestionData(data.results[0]); + setLoading(false); + }) + .catch(error => { + console.error("Error fetching question:", error); + setLoading(false); + }); + }; const selectAnswer = (selection) => { setSelectedAnswer(selection); @@ -16,14 +33,16 @@ function App() { let card; - if (selectedAnswer) { + if (loading) { + card =

Loading...

; + } else if (selectedAnswer) { card = ( ); - } else { + } else if (questionData) { let options = [ questionData.correct_answer, ...questionData.incorrect_answers, @@ -41,11 +60,11 @@ function App() {

Trivia App

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