zeropsi
zeropsi

Reputation: 694

Is there a way to get a download percentage from a fetch request in React?

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?

Upvotes: 3

Views: 5624

Answers (1)

Karthikeyan
Karthikeyan

Reputation: 321

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 => {
})

Upvotes: 4

Related Questions