Search⌘ K
AI Features

Implementing More of the Question Page

Explore how to implement more features of the question page by fetching question data asynchronously using a custom function. Learn to manage state with React hooks, apply strict equality checks, and render content conditionally with React Fragments to handle multi-element returns.

Adding a function to get a question

Let’s carry out some more steps to implement the question page a little more:

  1. In QuestionsData.ts, add a function that will simulate a web request to get a question:

Node.js
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 ...