How to show progress of Axios during get request (not download or upload)
Here's what worked for me in React:
const client = axios.create({ baseURL: 'http://localhost:10000/v1/client', timeout: 20000})let result = await client.get('/fetchMeSomething', { onDownloadProgress: progressEvent => { const total = parseFloat(progressEvent.currentTarget.responseHeaders['Content-Length']) const current = progressEvent.currentTarget.response.length let percentCompleted = Math.floor(current / total * 100) console.log('completed: ', percentCompleted) }}).then(res => { console.log("All DONE: ", res.headers) return res.data})
axios .get("download something", { onDownloadProgress: (progressEvent) => { let downloadCount = DownloadCount( progressEvent.timeStamp, progressEvent.total, progressEvent.loaded ); let percentCompleted = Math.round( (progressEvent.loaded * 100) / progressEvent.total ); setProgressing(percentCompleted); dispatch({ type: "downloading", payload: downloadCount.toFixed(1), }); }, }) .then((response) => {}) .catch((error) => { console.log(error); });
I think the reason why axios
exposes both onUploadProgress
and onDownloadProgress
is that you can easily perform some calculation on bytes being transferred. In case of simple server request, I think using a flag such as setting on
state = { loading: false}
and flip this to true
whenever you make your request is ideal. You may use a spinner as a mask if you wish to.