Implementing More of the Question Page
Learn to modify the question page in this section.
We'll cover the following...
Adding a function to get a question
Let’s carry out some more steps to implement the question page a little more:
In
QuestionsData.ts
, add a function that will simulate a web request to get a question:
export const getQuestion = async (questionId: number): Promise<QuestionData | null> => {await wait(500);const results= questions.filter(q => q.questionId ===questionId);return results.length === 0 ? null : results[0];};
We have used the array filter
method to get the question for the passed-in questionId
.
Notice the type annotation for the function’s return type. The type passed into the Promise
generic type is Question | null
, which is called a union type.
Note: A union type is a mechanism for defining a type that contains values from multiple types. If we think of a type as a set of values, then the union of multiple types is the same as the union of the sets of values.
So, the function is expected to asynchronously return an object of the QuestionData
or ...