I'm trying to upload to Firebase storage some file, chosen earlier in input element of a React form
it's a handler: pass file object to uploader and waits (I'd like to do so) for the return from it.
// comes from input-type element, contains icon picture
handleIconFile =(e) => {
const iconFile = e.target.files[0]
// try to upload in order to get download url
const downloadURL = uploadFile(iconFile, ()=>{
// takes some time ...
console.log(downloadURL);
// store url to state
this.setState({ downloadURL })
})
}
it's uploader: it was taken from firebase docs and added return statement in success handler
/** takes File Object to upload to storage
returns url for download this file from firebase */
uploadFile = (iconFile) => {
// root reference
const fileName = iconFile.name
console.log(fileName);
// const metadata = { contentType: 'image/jpeg' }
const storageRef = storage.ref()
const uploadTask = storageRef.child('/icon/'+ fileName).put(iconFile)
// 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', function(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
var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
console.log('Upload is ' + progress + '% done');
}, function(error) {
// Handle unsuccessful uploads
console.log('error:', error);
}, function() {
// Handle successful uploads on complete
var downloadURL = uploadTask.snapshot.downloadURL;
// console.log(downloadURL);
return downloadURL // <--- I did add this myself in order to return it back to handler
});
}
file is loaded successfully. in console I see: Upload is 0% done Upload is 100% done
problem is: downloadURL don't return to handler back.
I can see it in success section of uploader -- // console.log(downloadURL); , but can't see it anywhere else.
uploadFilefunction , like :} var downloadURL = uploadTask.snapshot.downloadURL; backFire(downloadURL); }) const backFire = (url) => { console.log(url); this.setState({ downloadURL: url }) }looks weird, but its the only way I found to return something in asynchronous world.