Open Sulton88Mehron90 opened 1 year ago
In useEffect
after getting data from the API we must decode it convert any special characters back to a human-readable form.
The formattedQuestions is an array of objects, where each object represents a formatted trivia question. Let's break down what's happening inside the .map() function:
const decodedQuestion = decodeURIComponent(rawQuestion.question);
: This line decodes the URI components of the question text, converting any special characters back to a human-readable form.
const decodedCorrectAnswer = decodeURIComponent(rawQuestion.correct_answer);
: This line decodes the URI components of the correct answer text.
const decodedIncorrectAnswers = rawQuestion.incorrect_answers.map(decodeURIComponent);
: This line decodes each incorrect answer in the array using .map() and decodeURIComponent.
return {...}
: Finally, the function returns an object that has an
id, question, correctAnswer, and options.
**id: \${index}-${Date.now()}`**
: The id` is created by concatenating the current array index and the current timestamp. This ensures each question has a unique identifier.
question
: decodedQuestion: Stores the decoded question text.
correctAnswer
: decodedCorrectAnswer: Stores the decoded correct answer text.
options: [...decodedIncorrectAnswers, decodedCorrectAnswer].sort(() => Math.random() - 0.5)
: This line combines the incorrect answers and the correct answer into a single array and then randomizes the order; used for displaying the multiple-choice options.
So, each object in formattedQuestions will look something like this:
{
"id": "0-1631902423239",
"question": "What is the capital of France?",
"correctAnswer": "Paris",
"options": ["London", "Berlin", "Paris", "Madrid"]
}
This array of formatted questions is then set as the state variable flashcards via setFlashcards(formattedQuestions);
.
keep the App component uncluttered.
What is URI ?
URI stands for Uniform Resource Identifier. It is a string of characters that identify a name or a resource on the Internet. URIs can be broken down into two types:
A URL is a specific type of URI that not only identifies a resource but also explains how to access it, typically over the web. For example,
https://www.example.com/page is a URL, and it is also a URI.
In the context of the code, decodeURIComponent is used to decode a URI component. This is often necessary when you're receiving encoded URLs or URI components via an API. For example, if spaces in a string are encoded as
%20
, decodeURIComponent would convert them back to actual space characters.Here's a quick example:
Encoded:
Hello%20World%21
Decoded:Hello World!
The decodeURIComponent function helps to ensure that any special characters in the question or answers fetched from the API are converted back to their original form, making them readable and usable in your application.
Below snippet of data fetched from API for this project.