Firebase (web) - add user data upon signup

江枫思渺然 提交于 2020-04-18 05:46:15

问题


I am having some troubles with the following case:

I am using email login functionality in Firebase Auth. Everything works fine. As part of the registration form however, there is a user name field. When the form gets submitted, the following action is performed:

const response = await auth.createUserWithEmailAndPassword(email, password);
await response.user?.updateProfile({
   displayName: name
});

This is properly updating the user profile with the display name. The problem is that right after createUserWithEmailAndPassword finishes, it fires onAuthStateChanged, which is the only place the user is being controlled in the app's local state. Once the callback is fired however, the display name is still not known and this causes the first render of the app after registration to not be aware of the name of the user. If the page gets refreshed, the name would appear, as it's now persisted.

I could persist the user data in the state myself, but this is losing some of the benefits of using the automatic subscription.

Does any of you solved this problem is a nicer way?

Thanks!

Edit: I have also found a method in auth, called updateCurrentUser and I have tried calling it after the update profile has finished. This is however not triggering the onAuthStateChanged, as stated in the docs.


回答1:


I think you could try this

firebase.auth().createUserWithEmailAndPassword(email, password).then(function(user) {
    var user = firebase.auth().currentUser;
    user.updateProfile({
        displayName: name
    }).then( ()=>  {
        alert(user.displayName + " " + user.email);
    })   
});

Edit 1:

  1. I forgot ")" at the end
  2. add .then to show alert that the user is updated. Note: for test purpose disable my firebase.auth().onAuthStateChanged(..) so it won't redirect and the alert will show

Edit 2: Nvm the problem is with onAuthStateChanged it won't get updated




回答2:


An update of a user profile does not result in any auth state listener callbacks to be triggered. Listeners are only invoked when the user is newly signed in or signed out since the last time the listener was invoked. If you need to reload a user's profile after an update, you can call reload() on the user object.



来源:https://stackoverflow.com/questions/61228195/firebase-web-add-user-data-upon-signup

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!