How do I set the displayName of Firebase user?

2020-06-08 14:07发布

问题:

According to the JS Auth documentation on the Firebase website, it only shows how to get the displayName and how to update displayName. So I tried to update it. But it is sort of not logical, because how can you update something without creating it.

So my question here is, how can I set displayName of user during registeration?

function createUser(email, password) {
    firebase.auth().createUserWithEmailAndPassword(email, password).catch(function (error) {
        error.message.replace(".", "");
        alert(error.message + " (" + error.code + ")");
        document.getElementById("password").value = "";
    });
    if (firebase.auth().currentUser != null) {
        firebase.auth().currentUser.updateProfile({
            displayName: document.getElementById("name").value
        }).then(function () {
            console.log("Updated");
        }, function (error) {
            console.log("Error happened");
        });
    }
}

I have already tried this and it has been proven not to work...

Sincerely, Farouk

回答1:

You have to chain the request:

firebase.auth().createUserWithEmailAndPassword(email, password)
.then(function(result) {
  return result.user.updateProfile({
    displayName: document.getElementById("name").value
  })
}).catch(function(error) {
  console.log(error);
});`


回答2:

I could´t use ({displayName: name}) directly (sintaxe error in editor). Then, I found another way:

UserUpdateInfo updateInfo = UserUpdateInfo();
updateInfo.displayName = name;
result.user.updateProfile(updateInfo);

This is in Dart (I am using Firebase with Flutter).