问题
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:
- I forgot ")" at the end
- add
.then
to show alert that theuser
is updated. Note: for test purpose disable myfirebase.auth().onAuthStateChanged(..)
so it won't redirect and thealert
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