joltup / rn-fetch-blob

A project committed to making file access and data transfer easier, efficient for React Native developers.
MIT License
2.81k stars 772 forks source link

Cancel Method Not working #687

Open ebeliejinfren opened 3 years ago

ebeliejinfren commented 3 years ago

i use rn-fetch-blob to download file in React Native every thing work correct but when use cancel method according to doc, cancelling not work and got error "fileFetchPromise Is Not Defained"

const download = () => {
  let fileOptions = { fileCache: true, path: path, };
  const fileFetchPromise = config(fileOptions).fetch('GET', fileUrl);
  fileFetchPromise.progress({ interval : 1000 }, (received, total) => {
    let persend = 100 * received / total;
    setSaved(persend.toFixed(0));
    setReceived(bytesToSize(received));
    setTotalSize(bytesToSize(total));
  });

  fileFetchPromise.then((data) => {
    setSaved('100');
  }).catch((err) => {
    setSaved('0')
  })
}

const cancelDownload = () => {
  fileFetchPromise.cancel((err) => {})
}
nadav2051 commented 3 years ago

fixed it in my fork, you can look: https://github.com/nadav2051/rn-fetch-blob/commit/6af66cbb0de74b851a84bb6e3da1ba8679f960eb https://github.com/nadav2051/rn-fetch-blob/commit/f979791099528f7c2f69a9e240282d75ddfde1d4

majirosstefan commented 2 years ago

@nadav2051 Not working, I used this patch-package diff:

diff --git a/node_modules/rn-fetch-blob/polyfill/Fetch.js b/node_modules/rn-fetch-blob/polyfill/Fetch.js
index 3ecb591..979f714 100644
--- a/node_modules/rn-fetch-blob/polyfill/Fetch.js
+++ b/node_modules/rn-fetch-blob/polyfill/Fetch.js
@@ -40,6 +40,7 @@ class RNFetchBlobFetchPolyfill {
           promise = Blob.build(body).then((b) => {
             blobCache = b
             options.headers['Content-Type'] = 'multipart/form-data;boundary=' + b.multipartBoundary
+            options.headers['content-type'] = 'multipart/form-data;boundary=' + b.multipartBoundary
             return Promise.resolve(RNFetchBlob.wrap(b._ref))
           })
         }
@@ -58,10 +59,14 @@ class RNFetchBlobFetchPolyfill {
       // task.then is not, so we have to extend task.then with progress and
       // cancel function
       let progressHandler, uploadHandler, cancelHandler
+
+      let scopedTask = null
+
       let statefulPromise = promise
           .then((body) => {
             let task = RNFetchBlob.config(config)
-              .fetch(options.method, url, options.headers, body)
+                .fetch(options.method, url, options.headers, body)
+            scopedTask = task
             if(progressHandler)
               task.progress(progressHandler)
             if(uploadHandler)
@@ -86,12 +91,11 @@ class RNFetchBlobFetchPolyfill {
       }
       statefulPromise.cancel = () => {
         cancelHandler = true
-        if(task.cancel)
-          task.cancel()
+        if(scopedTask && scopedTask.cancel)
+          scopedTask.cancel()
       }

       return statefulPromise
-
     }
   }