我正在尝试在 .下面的代码仅检索当前登录用户的数据。我对如何按用户名过滤数据感到非常困惑,并尝试了多种方案但无济于事。
我已经尝试使用 firebase 中的 equalTo 方法,但似乎无法让它工作。如何访问数据结构的第二个子级并仍然检索其下面的数据?错误出现在friendRequestFetch 函数中。
JSON
{
"requests" : {
"RIXXnKMGxYRPBTe1kBUsNUV9eFL2" : {
"NQgSxcVKm1N3tnkykUevBM45JLn2" : {
"name" : "Tom Hanks",
"photoURL" : "https://firebasestorage.googleapis.com/v0/b/myapp-d0755.appspot.com/o/profilePhotos%2FNQgSxcVKm1N3tnkykUevBM45JLn2?alt=media&token=7822d763-e1e0-421e-88bf-836b34184c2c",
"receiver" : "RIXXnKMGxYRPBTe1kBUsNUV9eFL2",
"sent" : 1557800380001,
"status" : "pending",
"uid" : "NQgSxcVKm1N3tnkykUevBM45JLn2"
}
}
}
}
代码
export const sendFriendRequest = (item) => {
const { currentUser } = firebase.auth()
return (dispatch) => {
firebase.database().ref(`/friends/requests/${item.uid}/${currentUser.uid}`)//sting interpolation
.set({
uid: currentUser.uid,
//userName: firebase.database().ref(`/users/${currentUser.uid}`).snapshot.val().userName,
name: currentUser.displayName,
photoURL: currentUser.photoURL,
status: "pending",
sent: firebase.database.ServerValue.TIMESTAMP
})
.then(() => {
dispatch({
type: SEND_FRIEND_REQUEST
});
});
};
};
export const friendRequestFetch = () => {
const { currentUser } = firebase.auth()
return (dispatch) => {
firebase.database().ref('/friends/requests')
.on('value', snapshot => {
snapshot.forEach(child => { //anytime we get any value call function with an object thats describing the data thats sitting in there
dispatch({
type: FRIEND_REQUEST_FETCH_SUCCESS,
payload: child.val() // this is how we get access to the data at this ref
});
});
});
};
};
我需要子值,但仅适用于当前登录的用户。
最佳答案
您可以通过以下两种方法获取当前登录的用户。
1)
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
} else {
// No user is signed in.
}
});
2)
var user = firebase.auth().currentUser;
在您的情况下currentUser
等于firebase.auth()
。不是 firebase.auth().currentUser; 。我认为问题就在那里。
有关更多信息,请参阅 firebase 文档 https://firebase.google.com/docs/auth/web/manage-users
关于javascript - 如何在firebase中检索当前用户数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56122328/