我正在尝试将使用过的 UID 添加到实时数据库中,但是当我这样做时,UID 会重新定义,我不确定为什么会这样。
这是我的 JS
var userUID;
firebase.auth().onAuthStateChanged(function (user) {
if (user) {
userUID = user.uid;
} else {}
});
//Creating the Database for the Users using realtime mf (SAVE THE DATABSE INFO)
database.ref('users/' + userUID).set({
Name: name,
Email: email,
Password: password,
Industry: industry,
Birthday: birthday
});
这是实时数据库中的输出
谢谢
最佳答案
正如 charlie 所评论的,onAuthStateChanged
是异步触发的。这意味着您的 set()
调用当前在设置 userUID
之前运行。
通过添加一些适当的日志语句,您可以最轻松地看到这一点:
console.log("Starting to listen to auth state");
firebase.auth().onAuthStateChanged(function (user) {
console.log("Got auth state");
});
console.log("Started to listen to auth state");
运行此代码时,输出为:
Starting to listen to auth state
Started to listen to auth state
Got auth state
这可能不是您所期望的,但它完全解释了为什么您在数据库中得到undefined
。当您运行 database.ref('users/' + userUID).set({...
时,userUID
尚未设置。
修复方法很简单:将需要 userUID
的代码移动到获取它的方法中:
var userUID;
firebase.auth().onAuthStateChanged(function (user) {
if (user) {
userUID = user.uid;
database.ref('users/' + userUID).set({
Name: name,
Email: email,
Password: password,
Industry: industry,
Birthday: birthday
});
}
});
关于javascript - 我正在尝试将使用过的 UID 添加到实时数据库中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53716383/