Search code examples
javascriptfirebasegoogle-cloud-storageprogressive-web-appsoffline

Trigger Code When Uploading a File to Firebase Cloud Storage When Offline


Here's the code Firebase uses in its docs as a reference for uploading files to Firebase Cloud Storage.

import { getStorage, ref, uploadBytesResumable, getDownloadURL } from "firebase/storage";

const storage = getStorage();
const storageRef = ref(storage, 'images/rivers.jpg');

const uploadTask = uploadBytesResumable(storageRef, file);

// Register three observers:
// 1. 'state_changed' observer, called any time the state changes
// 2. Error observer, called on failure
// 3. Completion observer, called on successful completion
uploadTask.on('state_changed', 
  (snapshot) => {
    // Observe state change events such as progress, pause, and resume
    // Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
    const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
    console.log('Upload is ' + progress + '% done');
    switch (snapshot.state) {
      case 'paused':
        console.log('Upload is paused');
        break;
      case 'running':
        console.log('Upload is running');
        break;
    }
  }, 
  (error) => {
    // Handle unsuccessful uploads
  }, 
  () => {
    // Handle successful uploads on complete
    // For instance, get the download URL: https://firebasestorage.googleapis.com/...
    getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) => {
      console.log('File available at', downloadURL);
    });
  }
);

Looking at this example code above, I expect that when in an offline state after the first 'running' case is fired, the next 'state_changed' update will trigger due to no internet connection, and then the 'pause' case will fire.

Inside the pause case, I want to write some code to execute in cases where the file is being uploaded when offline. However the 'pause' case never fires when in an offline state or when a connection is lost midway. The error callback also does not run. The code simply just hangs there until a connection can be made.

What's a good way to execute code that only needs to be run when offline (say to upload the file to local storage until a connection can be made) in the uploadTask.on() method.

Thanks in advance for any help!

TLTR: In the context of this example code above, what's the standard way to execute code that only needs to be run when offline (say to upload the file to local storage until a connection can be made) in the uploadTask.on() method?


Solution

  • Not having an internet connection is not considered an error condition by the Firebase SDK for Cloud Storage. Instead it will merely retry the operation with exponential backoff.

    The pause event is only fired when you call the pause() function yourself as far as I know and can see in the SDK source.