javascript - 为什么 displayName 没有得到更新?使用 onAuthChanged
问题描述
我正在使用 Redux 并坚持我的身份验证。onAuthChanged
使用 redux 工具包,我有一个从 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
}
});
}
});
};
};
然后,当我检查该用户是否存在文档时,如果不存在则创建一个。
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;
};
所以这就是我的问题所在。创建我的用户时displayName
始终为空,如何正确更新用户配置文件?似乎onAuthChanged
在它可以进行更新之前被触发,因此 displayName 将始终为 null 并且文档将不包含 displayName 属性
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);
});
};
};
解决方案
调用updateProfile
不会触发onAuthStateChanged
,因为身份验证状态不会改变。也无法延迟onAuthStateChanged
此处的触发,因为您只能在创建用户帐户后设置显示名称,这也将其登录。
我能想到的两个选择:
创建用户,设置其显示名称,将其注销,然后再次登录。然后后者将触发另一个
onAuthStateChanged
包含显示名称的内容。当您还调用
updateProfile
.
推荐阅读
- javascript - React Native 搜索以文本开头的单词
- python - 根据索引名称是否出现在列表中拆分 Pandas DataFrame
- neo4j - Neo4j/Cypher 尝试展开用户 ID 列表,创建一个通知并与所有匹配的用户建立关系
- php - 用户输入文本区域渲染 \n\r 而不是换行符
- python - python多索引列表
- c++ - 为可以存储在浮点数中的最大连续整数定义的常量?
- android - Android:在第一个活动中收到回调,而不是在第二个活动中
- r-markdown - 仅针对特定文档类型评估 Rmarkdown 代码块(html_document vs pdf_document)
- flutter - Flutter - 在 FutureBuilder 和 SliverList 中使用 ListView.builder - 滚动行为
- django-models - 如何将自定义字段添加到 ModelSerializer?