React Trivia App Using jService

Donovan Odom
3 min readAug 14, 2021

--

About 3 months into my course, and its time for project number 2. I decided to build a trivia application using an API called jService. You can find the documentation here.

I began by mapping out the component tree, then spending time outlining the logic of the application.

My component tree:

The rules:

A total of 50 individual questions will load.

Win by answering 5 questions in a row.

If you answer incorrectly, or skip a question, the count will

reset.

To begin, I implemented the useEffect & useState hook to fetch 50 random questions from the API at the App.js level:

Simple enough.

Continuing on the App.js level, I then implemented a couple functions to organize the questions in a manner that only displays one question object at a time:

Above, I used state to hold both my index value as index and my displayed question as displayQ. As index changes in the handleNext() function, my handleLoad() function updates my displayQ state. Together, these functions increment to the next object in the array of questions.

Then I used state to hold the input for whenever a user enters an answer as keyedAnswer:

Time to switch levels to Question.js

Below is the JSX I used to hold the displayQ data:

Notice the onClick event listener. This will become relevant later.

The ? after the category nested object was essential. There were questions that would load without a category key causing the app to crash. The ? in this case will first check for the existence of a nested object called category before attempting to access it’s value.

In the Answer.js component, we got to have a little fun with regex. (Admittingly, I know there is a far simpler regex code I could have used)

Nonetheless, the onClick event listener combined with a ternary operator effectively checks to see if keyedAnswer matches (to some acceptable degree based on the regex parameters provided) the correct answer based on the displayQ.answer value and initiates a correct() or removeDot() function accordingly:

The correct() function adds a “dot” string to the count array, which in the Counter.js component will display a green dot for every string. Once the count hits 5, the ternary operator triggers a few callback functions and redirects to the LeaderBoard.js component. If count has a length that is less than 5, the ternary operator triggers callback functions, including the one we named handleNext() which will load the next question.

The removeDot() function acts in opposition to the correct() function. It sets count back to an empty array and remains on the same question.

Anecdotally, to add a little flair, the handleConf() call back function runs confetti-js when the answer is correct.

GitHub Repo: https://github.com/div-donis/trivya

Deployed Site: https://trivya.netlify.app/

--

--

Donovan Odom

Software Engineer & all-things-tech enthusiast. Audio Engineer/Producer. Flatiron Alumni.