Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we use onDownloadProgress from axios for loading API?

I need to create a progress bar for loading API in a react project using axios, and I discovered the onDownloadProgress function for this, but I don't know if we can use it for get information like loading percentage for example or if it only for files download?

So I don't sure if we can get information about API loading with this function?

I tried to implement this function in my code :

componentWillMount() {
  axios.get('https://guillaumeduclos.fr/jd-portfolio/wp-json/wp/v2/posts')
  .then(response => {
    axios.onDownloadProgress = (progressEvent) => {
      let percentCompleted = Math.round( (progressEvent.loaded * 100) / progressEvent.total );
      console.log(percentCompleted);
    }
    this.setState({
      datas: response.data[0].acf.project_illustration.url,
      loading: false
    });
  })
  .catch(error => {
    if(error.response) {
      console.log(error.responderEnd);
    }
  });
}

The console.log() is not display.

like image 909
Guillaume Avatar asked Oct 30 '25 13:10

Guillaume


1 Answers

You need to pass the onDownloadProgress in as an option. It will print out "Infinity" because of the lengthComputable.

Here is a post regarding that issue: JQuery ajax progress via xhr

componentWillMount() {
axios.get('https://guillaumeduclos.fr/jd-portfolio/wp-json/wp/v2/posts', {
  onDownloadProgress: (progressEvent) => {
    let percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
    console.log(progressEvent.lengthComputable)
    console.log(percentCompleted);
  }
})
  .then((response) => {
    this.setState({
      datas: response.data[0].acf.project_illustration.url,
      loading: false
    })
  }).catch(error => {
    if (error.response) {
      console.log(error.responderEnd);
    }
  });

}

like image 89
V Soren Avatar answered Nov 02 '25 04:11

V Soren



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!