Global Progress Bar on API (s)call in React
Single Page Application(s) build with React often need to process many API requests while loading the application. Providing a user feedback while making API call is essential for good user experience.
Let’s take a look at a simple approach for displaying a progress indicator while these requests complete.
First, let’s create a reducer to keep track of the loading state. The store will have a simple counter of how many tasks are loading.
reducer/loading.js
When something such as an API request, heavy computation, or any other lengthy task starts running, we will commit a “START_LOADING” mutation. When it’s done running, we will commit a “FINISH_LOADING” mutation.
If state.loading
is 0, then nothing is loading. If state.loading
is greater than 0, then something is loading.
Next, let’s create an axios.js
service with Axios and hook it up to the loading store.
Axios exposes an interceptors
feature which allows hooking into the lifecycle of an Http request.
We are going to use interceptors to commit a START_LOADING
mutation upon start of a request, and FINISH_LOADING
upon end of a request. We’ll also need to commit FINISH_LOADING
upon any error.
utils/axios.js
Now, any http request made through our axios.js
service will automatically increment and decrement our loader.loading
state.
Finally, let’s hook this up to our Container.
What we are doing here is we are setting the max value of the progress-bar to the total number of request that was made.
Each time when the number of options request is made, the totalRequest gets incremented, setting the max attribute of progress-bar.
After getting the response, the loading value gets increment too, resulting same number of totalRequest and loading. Thus completing the chart.