Skip to content
Advertisement

Firebase Storage Web: uploadTask.cancel() is not working reactjs

I want to cancel the upload task at the click of a button. But it is not working(it returns false and I can view the file in the firebase storage console) below is the full code of the component

Upload.js

import React, { useState } from "react";
import { ref, uploadBytesResumable } from "firebase/storage";
import { storage } from "../../firebase";
import bookwall from "../../illustrations/bookwall.svg";

const Upload = () => {
  const [loading, setLoading] = useState(false);
  //used for cancel button
  const [cancel, setCancel] = useState(false);
  const formHandler = (e) => {
    e.preventDefault();
    const file = e.target[1].files[0];
    uploadFile(file);
  };

  const uploadFile = (file) => {
    if (!file) return;
    const storageRef = ref(storage, `files/${file.name}`);
    const uploadTask = uploadBytesResumable(storageRef, file);
    if(cancel === true){
      uploadTask.cancel();
      setLoading(false);
      setCancel(false);
      console.log('cancelled');
      console.log(`does upload task cancel work? ${uploadTask.cancel()}`);
    }
    
    //https://firebase.google.com/docs/reference/js/v8/firebase.storage.UploadTask
    uploadTask.on(
      "state_changed",
      //setting loading to true while the file upload is pending
      (snapshot) => {
        //to keep the upload button disabled till the upload is completed
        setLoading(true);
        console.log(snapshot.state)
        
      },
      //function for error
      (error) => {
        switch (error.code) {
          case 'storage/unauthorized':
            // User doesn't have permission to access the object
            alert('something went wrong while uploading this file :(')
            setLoading(false);
            break;
          case 'storage/canceled':
            // User canceled the upload
            console.log('the cancel method works')
            setLoading(false);
            setCancel(false);
            break;
          default:
            alert('something went wrong while uploading this file :(')
            setLoading(false);
        }
      },
      //function for successful completion
      () => {
        setLoading(false);
        console.log('the upload is successful');
      }
    );
    
    
  };
  return (
    <main className="upload">
      <form onSubmit={formHandler} className="upload-form">
        <h1>
          Add a new book for <br /> Everyone to read!
        </h1>
        <input
          type="text"
          className="gbooks-link"
          placeholder="Google Books Link"
          required
        />
        <label className="file-input-label">
          <input type="file" className="input" id="file-upload" required />
          Upload the book here
        </label>
        <div className="buttons-container">
          <button disabled={loading} type="submit" className="upload">
            Upload
          </button>
          {
            loading === true ?
            <button className="cancel" onClick={() => setCancel(true)}>
              Cancel
            </button>
            :
            null
          }
         
        </div>
      </form>
      <img src={bookwall} alt="a wall full of books" className="bookwall" />
    </main>
  );
};

export default Upload;

Here is what’s happening in the console after I click on cancel(after clicking upload and setting a file(img, 3.15mb))

the image link on imgur

if I just do

const uploadTask = uploadBytesResumable(storageRef, file);
console.log(`does upload task cancel work? ${uploadTask.cancel()}`);

it returns true and the upload actually gets cancelled

Advertisement

Answer

Turns out it was a scope-related issue… I had to make the uploadTask globally available by making it a react state to implement it in my code and I called the uploadTask.cancel() in my button callback…I used useEffect to monitor my uploadTask and I am doing setLoading(false) at the button callback instead of the error callback

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement