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);
});
}
);
TLTR: 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?
I assumed that when offline, after the first 'running' case is fired the next 'state_changed' update would be about there being no internet connection and would run the 'pause' case. In this case, I wanted to write some code to execute in cases where the file is being uploaded when offline. However this does not happen, and the 'pause' case never runs when offline 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 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.
Thanks in advance for any help!
CodePudding user response:
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.