Lesson 3. Custom hooks and classic async pattern 1. Handling asynchronous operations
Here we want to perform an HTTP request to an API and display the result. We also want to indicate if the component is currently loading the data or if something happened during the API call.
Result
The typical pattern when we want to load data to display asynchronously is to keep three state values:
- a flag to indicate if the request is pending (
loadinghere), - a flag to tell if an error occurred (
error), - and finally, a value containing the result of the request (
starship).
We update these three values during the lifecycle of the request:
- first, when the component is mounted (beginning of the
useEffect), - then just before we make the request,
- and finally when the request is completed, either successfully (
.then) or with an error (.catch).
Notice that, as we did in the previous lesson, we use an active flag to make
sure we don’t update the component’s local state when it is unmounted.
What if another component needs to get information about a starship, using the same request, but to present the data in a completely different way? Should we duplicate all the logic with these three states?