在React Firebase中,我正在尝试读取用户数据,并且快照给出的值为null
读取用户的代码是:
constructor() {
app.initializeApp(config);
/* Helper */
this.serverValue = app.database.ServerValue;
this.emailAuthProvider = app.auth.EmailAuthProvider;
/* Firebase APIs */
this.auth = app.auth();
this.db = app.database();
}
this.auth.onAuthStateChanged((authUser: any) => {
if (authUser) {
this.db.ref(`users/${authUser.uid}`)
.once('value')
.then(snapshot => {
const dbUser = snapshot.val(); // RETURNING NULL ISSUE ISSUE
// default empty roles
if (!dbUser.roles) {
dbUser.roles = {};
}
// merge auth and db user
authUser = {
uid: authUser.uid,
email: authUser.email,
emailVerified: authUser.emailVerified,
providerData: authUser.providerData,
...dbUser,
};
this.authUser = authUser;
next(authUser);
}).catch((err) => {
fallback();
});
} else {
fallback();
}
});
我已经检查authUser.uid是有效的uid-ojaGkteKX7evSEakaSlA8CZNBMJ3
我的Firebase中同一用户的屏幕截图:
实时数据库规则:
{
"rules": {
"users": {
".read":true,
"$uid": {
".read": true,
".write": "$uid === auth.uid"
}
}
}
}
云存储规则:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /users/{userId}{
allow read, delete;
}
}
}
答案 0 :(得分:0)
我假设在firebase中创建用户时,会在firebase中自动创建一个用户节点
如果您希望上述情况发生,则可以使用云功能,并使用firebase身份验证触发器:
const admin = require('firebase-admin');
const functions = require('firebase-functions');
admin.initializeApp();
exports.newUser = functions.auth.user().onCreate((user) => {
const root = admin.database().ref();
ref.child("users").child(user.uid).set({
email: user.email,
displayName: user.displayName
});
});
有关更多信息,您可以检查以下内容:
https://firebase.google.com/docs/functions/auth-events