Fetching Questions from an API
Fetching Questions from an API
Your app uses real data from the Open Trivia Database API. When the user selects a category, the app sends a request to fetch 10 questions of that category.
Example:
const fetchQuestions = async (categoryId) => {
const response = await fetch(`https://opentdb.com/api.php?amount=10&category=${categoryId}&difficulty=easy&type=multiple`);
const data = await response.json();
const formattedQuestions = data.results.map((q) => ({
question: q.question,
correctAnswer: q.correct_answer,
options: shuffle([...q.incorrect_answers, q.correct_answer]),
}));
setQuestions(formattedQuestions);
};The shuffle() function is used to randomize the order of the answer options for each question. This makes the quiz fair and unpredictable.


