I am working on my first Typescript and React project. I have a quiz app at https://quiz-time-69c35.web.app/
Right now selecting a category from the dropdown menu doesn't actually do anything. I need help using the selected option to fetch questions from the selected category.
I have an enum Category.
export enum Category {
ANY_CATEGORY = 0,
GENERAL_KNOWLEDGE = 9,
ENTERTAINMENT_BOOKS = 10,
ENTERTAINMENT_FILM = 11,
ENTERTAINMENT_MUSIC = 12,
ENTERTAINMENT_MUSICALS_AND_THEATRES = 13,
ENTERTAINMENT_TELEVISION = 14,
ENTERTAINMENT_VIDEO_GAMES = 15,
ENTERTAINMENT_BOARD_GAMES = 16,
SCIENCE_AND_NATURE = 17,
SCIENCE_COMPUTERS = 18,
SCIENCE_MATHEMATICS = 19,
MYTHOLOGY = 20,
SPORTS = 21,
GEOGRAPHY = 22,
HISTORY = 23,
POLITICS = 24,
ART = 25,
CELEBRITIES = 26,
ANIMALS = 27,
VEHICLES = 28,
ENTERTAINMENT_COMICS = 29,
SCIENCE_GADGETS = 30,
ENTERTAINMENT_JAPANESE_ANIME_AND_MANGA = 31,
ENTERTAINMENT_CARTOON_AND_ANIMATIONS = 32
}
A function to fetch questions at an endpoint.
export const fetchQuizQuestions = async (amount: number, category: Category, difficulty: Difficulty) => {
const endpoint = `https://opentdb.com/api.php?amount=${amount}&category=${category}&difficulty=${difficulty}&type=multiple`;
const data = await (await fetch(endpoint)).json();
return data.results.map((question: Question) => (
{
...question,
answers: shuffleArray([...question.incorrect_answers, question.correct_answer])
}
));
}
The user selects a category from a menu using the following onChange function. The selected option is stored in the state as selectedOption as type OptionType.
Console logging selectedOption here returns {value: "ENTERTAINMENT_BOOKS", label: "Books"}
onChange={(selectedOption) => {
const value = (selectedOption as OptionType).value;
setSelectedOption(value)
console.log(selectedOption)
}}
type OptionType = {
label: any;
value: any;
}
const [selectedOption, setSelectedOption] = useState<OptionType>();
The user then presses a button to call the following function and begin the quiz.
Console logging category or selectedOption only returns the value of selectedOption as string and not the whole object. Why is this case when the whole object was logged in the onChange function?
const startTrivia = async () => {
setLoading(true);
setGameOver(false);
const category = selectedOption
console.log(category)
const newQuestions = await fetchQuizQuestions(
TOTAL_QUESTIONS,
Category["SCIENCE_AND_NATURE"],
Difficulty.HARD,
);
setQuestions(newQuestions);
setScore(0);
setUserAnswers([]);
setNumber(0);
setLoading(false);
}
How can I use the string from the value in selectedOption to look up the member in the Category enum?
I tried Category[category] and Category[category?.value] but neither of them worked.
I am brand new to Typescript so any feedback is appreciated and if I'm going about this in the wrong manner please let me know.