2

I am looking for a way to get the progress of a fetch request in my React app? Is there any way to plug into the fetch API to get some type of percentage loaded of the request that I can use to display to my users?

zeropsi
  • 682
  • 9
  • 24
  • Does this answer your question? [Fetch API Download Progress Indicator?](https://stackoverflow.com/questions/47285198/fetch-api-download-progress-indicator) – Amila Senadheera Jan 07 '22 at 15:03

1 Answers1

2

Using fetch method

To track download progress, we can use response.body property. It’s a ReadableStream – a special object that provides body chunk-by-chunk, as it comes. Readable streams are described in the Streams API specification. Unlike response.text(), response.json() and other methods, response.body gives full control over the reading process, and we can count how much is consumed at any moment.

// Start the fetch and obtain a reader
let response = await fetch(url);

const reader = response.body.getReader();

// get total length
const contentLength = +response.headers.get('Content-Length');

// read the data
let receivedLength = 0; // received that many bytes at the moment
let chunks = []; // array of received binary chunks (comprises the body)
while(true) {
  const {done, value} = await reader.read();

  if (done) {
    break;
  }

  chunks.push(value);
  receivedLength += value.length;

  console.log(`Received ${receivedLength} of ${contentLength}`)
}

Please note currently upload track is not possible in fetch method. For that we should use XMLHttpRequest.

Reference : https://javascript.info/fetch-progress

Using axios class :

axios.request({
    method: "post", 
    url: url, 
    data: data, 
    onUploadProgress: (p) => {
      console.log(progress); 
    }
}).then (data => {
})
Karthikeyan
  • 183
  • 1
  • 8