Search code examples
reactjsreact-hooksaxiosdownloadprogress-bar

React - single progress bar for multiple downloads


I want to download files simultaneously, but I want to get the progress of the download in a single progress bar.

I already have the code to download the assets, just need the best way to represent it.

Promise.all(arr.map((endpoint) => axiosInstance.get(endpoint.url,{
onDownloadProgress: (progressEvent) =>{
  let percentCompleted = Math.round(progressEvent.loaded * 100 / 
  progressEvent.total);
  console.log(progressEvent.lengthComputable);
  console.log("progress completed : " + percentCompleted);
},
responseType:"arraybuffer",
headers: {
  'Content-Type': 'application/json',
}
}))

Edit:

The accepted answear helped me and now I have a progress bar with the percentage of all downloads simultaneously

enter image description here


Solution

  • After a little bit of digging, I found this:

    let progress = 0;
    const arr = [...]; // <request_1>, <request_2>, ...<request_n>
    const arrLen = arr.length;
    
    Promise.all(
      arr.map((endpoint) => {
        let previous = 0;
    
        return axios.get(endpoint, {
          onDownloadProgress: (progressEvent) => {
            const current = Math.round(
              (progressEvent.loaded * 100) / progressEvent.total / arrLen
            );
    
            progress += current - previous;
            console.log(progress);
    
            previous = current;
          },
          responseType: "arraybuffer",
          headers: {
            "Content-Type": "application/json",
          },
        });
      })
    );
    

    P.S: This is a quick solution.

    Resources
    1. Progress bar for multiple ajax requests with stages of completion. Is it possible?