This is a very common scenario and it is important to handle it properly. I will share the different ways you can handle asynchronous requests in dynamic React component including handling all stages of the request.
Lets consider the choices a developer can make.
Display nothing until the request is complete
This is the easiest thing to do. Show nothing unless the data exists.
Consider a component that has a state object containing an array property like this:
The items must be requested from an API resource, so they are initially empty.
The componentDidMount function contains the call to a separate asynchronous function.
The render function looks like this:
This method will show an empty space for a moment until the request has completed and the state is updated with the new results.
This delay of the render can cause confusion for the user as the user is not aware that the component is loading.
It not very graceful.
Display a loading message
To improve upon the first method, the next best thing to do is to display a loading message until the request has completed.
For this we can add another property to the state object called 'isLoading'.
This value is initially 'true' until the request has completed.
Our render function now has a conditional statement which will render a loading message.
Now the user is aware that the component is loading. No more confusion... That is unless the API request has failed.
If the request fails, then the user cannot tell if there has been an error with the request or if there are simply no results to show.
Handle all stages of the request
To combat this problem, we need to identify the 4 stages of a dynamic component:
- Idle
- Loading
- Success
- Fail
At the beginning of the dynamic component lifecycle, before any request is made, it is in the 'idle' state.
Once the request is made to fetch the data, it is changed to the 'loading' state. Then depending on the response, it will change to the 'success' or 'fail' state.
To implement these stages, we need to make a change to the state object:
Now we are using the 'loadState' property to identify the stage of the request process. We must change the componentDidMount function to reflect the 'loadState' values.
Our render function can be changed to this:
The render function now handles all stages of the dynamic request gracefully and will even show an error message if the request has failed.