Mehdi Faraji
Mehdi Faraji

Reputation: 3846

How can I get the onDownloadProgress percentage with axios get method?

Here is my code :

React.useEffect(() => {
        axios
            .get('https://jsonplaceholder.typicode.com/photos', {
                onDownloadProgress: (progressEvent) => {
                    let percentCompleted = Math.round(progressEvent.loaded * 100 / progressEvent.total);
                    console.log(progressEvent.lengthComputable);
                    console.log(percentCompleted);
                }
            })
            .then((response) => {
                console.log('response done');
            })
            .catch((error) => {
                console.log(error.message);
            });
    }, []);

And this is the console.log :

false
Infinity
false
Infinity
response done

I get infinity while trying to get the get method progress event . How can I get the exact percentage for the axios get method ?

Upvotes: 2

Views: 4621

Answers (2)

Spartan K8
Spartan K8

Reputation: 21

@Mehdi thanks for you question; I was having the same issue with getting infinity as the percentageCompleted inside the axios function onDownloadProgress. I agree the issue is due to the URL that we are downloading from. In my case I wasn't able to alter the URL so I altered the code to check if infinity. It is't perfect but does allow to show & hide a progress spinner (not a progress bar):

  onDownloadProgress(progressEvent) {
    const percentage = Math.round((progressEvent.loaded * 100) / progressEvent.total);
    setProgress(percentage);
    if (percentage === 100 || !percentage.isInFinite) {
      setTimeout(() => {
        setLoading(false);
      }, 400);
    }
  }

Upvotes: 2

Mehdi Faraji
Mehdi Faraji

Reputation: 3846

I solved the issue by using another api for get request . Simply the jsonplaceholder api doesn't have progress value for the get request .

axios.get('https://systran-systran-platform-for-language-processing-v1.p.rapidapi.com/translation/text/translate',
 { onDownloadProgress: (progressEvent) => {

     let percentCompleted = Math.round(progressEvent.loaded * 100 / 
     progressEvent.total);
     console.log(progressEvent.lengthComputable);
     console.log(percentCompleted);

  }
})

Upvotes: 0

Related Questions