Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

47 changes: 34 additions & 13 deletions src/App.jsx
Original file line number Diff line number Diff line change
@@ -1,29 +1,49 @@
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 = <div>Loading...</div>;
} else if (selectedAnswer) {
// Render ResultCard if an answer is selected
card = (
<ResultCard
correct={selectedAnswer === questionData.correct_answer}
answer={questionData.correct_answer}
/>
);
} else {
// Shuffle options and render QuestionCard if no answer is selected
let options = [
questionData.correct_answer,
...questionData.incorrect_answers,
Expand All @@ -36,16 +56,17 @@ function App() {
/>
);
}

return (
<div className="w-100 my-5 d-flex justify-content-center align-items-center">
<div style={{ maxWidth: "45%" }}>
<h1 className="text-center">Trivia App</h1>
<button className="btn btn-success">Next Question</button>
<button className="btn btn-success" onClick={fetchNewQuestion}>
Next Question
</button>
{card}
</div>
</div>
);
}

export default App;
export default App;