Skip to content

Instantly share code, notes, and snippets.

@nyancodeid
Created July 19, 2021 13:05
Show Gist options
  • Save nyancodeid/d67a7c8d83decb093bf101c1d711b7f9 to your computer and use it in GitHub Desktop.
Save nyancodeid/d67a7c8d83decb093bf101c1d711b7f9 to your computer and use it in GitHub Desktop.
Fetch With Progress

Fetch with Progress (XMLHttpRequest Implementation)

/**
 *
 * @param {String} url
 * @param opts
 * @param {Function} onProgress
 * @returns {Promise<String>}
 */
export const fetchWithProgress = (url, opts={}, onProgress) => {
  return new Promise( (res, rej)=>{
    const xhr = new XMLHttpRequest();
    xhr.open(opts.method || 'get', url);
    for (const k in opts.headers||{}) {
      if (opts.headers.hasOwnProperty(k)) {
        xhr.setRequestHeader(k, opts.headers[k]);
      }
    }
    xhr.onload = e => res(e.target.responseText);
    xhr.onerror = rej;
    if (xhr.upload && onProgress)
      xhr.upload.onprogress = onProgress; // event.loaded / event.total * 100 ; //event.lengthComputable
    xhr.send(opts.body);
  });
}
const onProgressHandler = (event) => {
  const calc = event.loaded / event.total * 100;
  console.log(`Progress ${calc}%`);
}

const response = await fetchWithProgress('/upload', { method: 'POST' }, onProgressHandler);

console.log(JSON.parse(response));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment