3

I want to implement the loading spinner/bar for every API calls made in react components. Instead of the typical way of implementing it in boolean state during request/response, is there a way that react can actually detect it in HOC? Like how it can be achieved in XHTML by using ajaxStatus primefaces.

Yusuf
  • 33
  • 1
  • 4
  • This isn't React's but developer's responsibility to detect requests. The question doesn't even specify how you do requests. – Estus Flask Sep 28 '18 at 06:14

2 Answers2

2

Try to use the axios-progress-bar package in case you're using Axios for API calls.

It works automatically, detects every API calls using Axios.

It's also very easy to use.

enter image description here

Using along with Axios, there are three steps to implement:

S1. Add these packages as usual

yarn add axios
yarn add axios-progress-bar

S2. In the index.js, add these lines:

import { loadProgressBar } from 'axios-progress-bar'
loadProgressBar()

S3. In the index.html, add this line:

<link rel="stylesheet" type="text/css" href="https://cdn.rawgit.com/rikmms/progress-bar-4-axios/0a3acf92/dist/nprogress.css" />
You Nguyen
  • 9,961
  • 4
  • 26
  • 52
  • 1
    @Yusuf on Stack Overflow, you might consider upvoting an answer in case it's useful. This way will make our community much better where everyone receives something for their contribution. Moreover, "Avoid comments like "+1" or "thanks" on Stack Overflow. – You Nguyen Oct 01 '18 at 01:57
2

As explained in this long-standing question, this can be done by patching APIs that can do HTTP requests, XMLHttpRequest and fetch. Changing global behaviour in non-standard way for individual purposes is discouraged.

In order to keep an eye on requests, API calls should be augmented with the code that counts started and finished requests. It's not enough to set boolean state because there could be simultaneous requests.

Axios is well-known library that offers features to do this. It was modeled after AngularJS $http and introduces the concept of interceptors which can be used for the specified purpose without wrapping every HTTP request API call.

axios-progress-bar that was linked in another answer is a good example of how this is done with Axios. It basically sets up an interceptor to count requests and notify progress bar component when counter value changes from 0 and back. It can be used with little changes with React component instead of non-React progress bar.

Estus Flask
  • 206,104
  • 70
  • 425
  • 565