[Vuejs]-Progress bar when running Axios in Vuex

0๐Ÿ‘

โœ…

You can get the progress of the HTTP transfer like this

axios.post(url, data, {
  headers: 
  {
    Authorization: 'Bearer ' + context.state.token
  },
  onUploadProgress: (event) =>
  {
    const percentUploaded = event.total ? Math.round((event.loaded * 100) / event.total) : 0;
    // show or update the progressbar
  },
  onDownloadProgress: (event) =>
  {
    const percentDownloaded = event.total ? Math.round((event.loaded * 100) / event.total) : 0;
    // show or update the progressbar
  }
})
.then(response => 
{
  // do something with response.data;
})
.catch(error => 
{
  // show an error alert;
})
.finally(() => 
{
  // nothing to do
});

The POST request will first upload the file and will update the upload progress, then it will download the response from the server and will update the download progress. The latter can be only measured reliably if the server sends Content-Length header.

It is difficult to make a combined progressbar because we do not know how many bytes will represent 100% on the combined progressbar until we receive the Content-Length header from the server and it is already too late when it comes. So you can simply show 2 progressbars โ€“ one for each direction of the HTTP transfer.

0๐Ÿ‘

Only thing you can do is to fake the values. You never know in beforehand what will be the size of the returned content. And the time elapsed until the Server begins returning anything is often times bigger than the time spent on actual downloading the response.

There are plenty of ways to take this behaviour, for example see here: https://www.npmjs.com/package/axios-progress-bar

Leave a comment