I want to add the display name to the user that was just created. But when I createUserWithEmailAndPassword it sais my currentUser is null. Anything wrong?
var n
createUserWithEmailAndPassword
is an asynchronous call like almost every other function in Firebase. You create the user (most likely successfully) but then immediately after you try and grab the currentUser
. In almost every case you will be attempting to get the currentUser
before Firebase has finished creating your user.
Rewrite inside callback:
firebase.auth().createUserWithEmailAndPassword(email, password).then(function(user) {
// [END createwithemail]
// callSomeFunction(); Optional
// var user = firebase.auth().currentUser;
user.updateProfile({
displayName: username
}).then(function() {
// Update successful.
}, function(error) {
// An error happened.
});
}, function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// [START_EXCLUDE]
if (errorCode == 'auth/weak-password') {
alert('The password is too weak.');
} else {
console.error(error);
}
// [END_EXCLUDE]
});
.then
will be called upon success and function(error)
will be called upon error. You want to set your user after user creation was successful.
Some people don't like the nested callbacks so you could create a function that gets the current user and call the function upon success.
Docs:
Firebase Promises
Async, callbacks