Getting a question from the REST API

Let's use our http function to get a single question from our REST API:

  1. We'll start by clearing out the current implementation, like so:
export const getQuestion = async (
questionId: number,
): Promise<QuestionData | null> => {
// TODO - make the request
// TODO - return null if the request fails or there is a network
error
// TODO - return response body with correctly typed dates if
request is successful
};

  1. Let's make the request and then return null if the request fails or there is a network error:
export const getQuestion = async (
questionId: number,
): Promise<QuestionData | null> => {
try {
const result = await http<undefined, QuestionDataFromServer>({
path: `/questions/${questionId}`,
});
if (result.ok && result.parsedBody) {
// TODO - return response body with correctly typed dates if
request is successful
} else {
return null;
}
} catch (ex) {
console.error(ex);
return null;
}
};
  1. Return the response body with correctly typed dates if the request is successful:
export const getQuestion = async (
questionId: number,
): Promise<QuestionData | null> => {
try {
const result = await http<undefined, QuestionDataFromServer>({
path: `/questions/${questionId}`,
});
if (result.ok && result.parsedBody) {
return mapQuestionFromServer(result.parsedBody);
} else {
return null;
}
} catch (ex) {
console.error(ex);
return null;
}
};
  1. When we save the changes and go to the question page in the running app, we will see the question correctly rendered on the screen:

We didn't have to make any changes to any of the frontend components. Nice!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.23.102.216