-2

I wanna build a progress bar for REST calls of my project, like react-redux-spinner, when user click a button to start a asynchronous action, the progress bar appear and when the action is finished the progress bar will be filled out.

I know that the asynchronous action is indeterminate, So how react-redux-spinner show the indeterminate time duration?

Is there a way to determine REST call time duration?

AmerllicA
  • 29,059
  • 15
  • 130
  • 154

2 Answers2

1

If you use XMLHttpRequest there is progress action that you can listen to:

var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt) {
   if (evt.lengthComputable) {
      var percentComplete = evt.loaded / evt.total;
      //Do something with upload progress here
   }
}, false);

xhr.addEventListener("progress", function(evt) {
    if (evt.lengthComputable) {
        var percentComplete = evt.loaded / evt.total;
        //Do something with download progress
    }
}, false);

Look at original question: What is the cleanest way to get the progress of JQuery ajax request?

donnyyy
  • 452
  • 3
  • 11
  • I'm useing `fetch` API, no `jQuery` and no `XHR`, I'm just using `fetch`. and Also your answer is about upload, is that right? just upload? can I use this answer method for other `REST` calls? like `GET` or `POST`? – AmerllicA Jun 26 '18 at 10:58
  • ``XHR`` is not related to jQuery and code before is pure js. No matter if your request is ``POST`` or ``GET`` - it relies on ``Content-Length`` header and data already (up)loaded from(to) server. This trick wont work with ``fetch``, but there is a [workaround](https://stackoverflow.com/questions/36453950/upload-file-with-fetch-api-in-javascript-and-show-progress/36454680) and [npm package](https://www.npmjs.com/package/fetch-progress) for it. – donnyyy Jun 26 '18 at 11:28
0

There is no way to know how long a request will take. You will 1. send the request and 2. receive the response. You have two options:

  • Use a loading bar and guess the time it will take, for example, make it load to 80% and process the last 20% when the request is received.
  • Use a spinner.

You'll have to ask yourself what the function of the loading bar/spinner will be. In the end, it is just something to show the user your application is doing something for them. The first solution gives them the impression of how long it'll take, whether you want to 'deceive' them into giving them an estimate or just be plain and show a spinner is up to you.

AmerllicA
  • 29,059
  • 15
  • 130
  • 154