I am using Redux and to persist my auth. Using redux toolkit I have an action that checks onAuthChanged
from Firebase Auth.
export const persistedSession = () => {
return async (dispatch) => {
dispatch(requestLogin());
firebaseAuth.onAuthStateChanged(async (user) => {
if (user) {
const currentUser = await createUserProfileDocument(user);
currentUser.on("value", (snapshot) => {
var data = snapshot.val();
if (data !== null) {
//Success
}
});
}
});
};
};
Then when I check if a document exists for this user and if not create one.
export const createUserProfileDocument = async (user) => {
if (!user) return;
const { uid, displayName, email } = user;
const userReference = database.ref("users");
userReference.once("value", (snapshot) => {
if (!snapshot.hasChild(uid)) {
userReference.child(uid).set({
...
});
}
});
return userReference;
};
So here is where my issue is. Upon creating my user displayName
is always null how can I update user profile correctly? It seems like onAuthChanged
is triggered before it can make an update so that displayName will always be null and document will not contain displayName property
export const registerUser = (value) => {
const { firstName, surname, email, password } = value;
return async (dispatch) => {
firebaseAuth
.createUserWithEmailAndPassword(email, password)
.then(async (result) => {
const user = result.user;
user.updateProfile({
displayName: `${firstName} ${surname}`,
})
})
.catch((error) => {
console.log("Unable to create user profile: ", error);
});
};
};
Calling updateProfile
does not trigger onAuthStateChanged
, as the authentication state doesn't change. There is no way to delay the triggering of onAuthStateChanged
here either, as you can only set the display name after the user account has been created, which signs them in too.
Two options that I can think of:
Create the user, set their display name, sign them out, and sign them in again. The latter will then trigger another onAuthStateChanged
with the display name included.
Explicitly write the display name to the database too, when you also call updateProfile
.