I have this database:
Main goal here is to display groupname if the members_uid matches the user. I'm able to get the user_uid using auth.currentUser
I'm currently just trying to print members/members
so I can use an if statement and display the results in my return statement(using React
)
What I've tried:
const db = getDatabase();
const dataRef = ref(db, '/groups');
onValue(dataRef, (snapshot) => {
const childKey = snapshot.key;
const data = snapshot.val()
const key = Object.keys(data);
console.log(data)
console.log(key)
console.log(childKey)
})
childKey
= groups
key
= returns all the firebase generated keys(e.g. -N02Qrg...)
data
= returns everything
How do I get groups/members/members uid
?
CodePudding user response:
Since you're reading groups
, the snapshot
that you get contains all data under that path. To navigate the snapshot, you have two main functions:
snapshot.child("name")
allows you to get the snapshot of a child node of which you know the name.snapshot.forEach()
allow you to loop over all child snapshots, typically when you don't know their name.
By combining these two, you can navigate any structure. For your JSON, I'd do something like this:
const db = getDatabase();
const dataRef = ref(db, '/groups');
onValue(dataRef, (snapshot) => {
snapshot.forEach((groupSnapshot) => {
console.log(groupSnapshot.key); // "-N02...R1r", "-N02...1T8"
console.log(groupSnapshot.child("g_id").val()); // "jystl", "nijfx"
snapshot.child("members").forEach((memberSnapshot) => {
... // each of the child snapshots of the `members` nodes
});
})
})
Note by the way that nesting multiple types of data under a single parent node is a common antipattern on Firebase, as explained in the documentation on structuring data, specifically the sections on avoiding building nests and keeping your data flat.