Reputation: 406
I am using this javascript code to upload an image to firebase storage then I want to update this image url to user's photoURL (firebase auth)
const fileButton = document.querySelector('#fileButton');
var imageURL;
fileButton.addEventListener('change', function(e) {
//get file
var file = e.target.files[0];
//create a storage reference
var storageRef = storage.ref('profilePictures/' + userUID + '.jpg');
//upload file
var task = storageRef.put(file);
//update progress bar
task.on('state_changed',
function progress(snapshot){
},
function error(err) {
},
function complete(){
storageRef.getDownloadURL().then(function(url) {
console.log(url);
imageURL = url;
})
.catch(function(error) {
// Handle any errors
console.log(error);
});
// window.location.replace('/profile');
var user = auth.currentUser;
user.updateProfile({
photoURL: imageURL
})
.then(function() {
// Update successful.
console.log(user);
})
.catch(function(error) {
// An error happened.
console.log(error);
});
}
);
});
image upload on storage is successfull but photoURL in user data is NOT SUCCESSFULL
uid: "t2TbJS6ut7NZH4UU8HeAVarGPOw2"
displayName: "Sachin Kumar"
photoURL: null
email: "[email protected]"
emailVerified: false
what I am doing wrong
Upvotes: 1
Views: 4569
Reputation: 73906
You need to wait for storageRef.getDownloadURL()
to finish before passing it to user.updateProfile
like:
function complete() {
storageRef.getDownloadURL().then(function(url) {
console.log(url);
imageURL = url;
// Now you have valid `imageURL` from async call
var user = auth.currentUser;
user.updateProfile({ photoURL: imageURL })
.then(function() { console.log(user) })
.catch(function(error) { console.log(error) });
})
.catch(function(error) { console.log(error) });
}
Upvotes: 2