Let's use our http function to get a single question from our REST API:
- 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
};
- 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;
}
};
- 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;
}
};
- 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!