score:1

Accepted answer

if you want to show the list of friends for a certain event, and you know the key of that event, you can do something like:

let eventkey = '-lrufqaslescaek2mqxu';
let eventref = firebase.database().ref('events').child(eventkey);
eventref.child('friends').once('value').then((snapshot) =>{
  let allfriendlist = [];
  snapshot.foreach((friendsnapshot) => {
    let data = friendsnapshot.val();
    alluserlist.push(data);
  });
  this.setstate({allfriendlist: allfriendlist});
});

some of the changes:

  • this code only listens for the specific path /events/-lrufqaslescaek2mqxu/friends. in fact, it could have used that path to listen to, i.e. firebase.database().ref('/events/-lrufqaslescaek2mqxu/friends').once('value'...`
  • the snapshot we get from this contains multiple friends, so we loop over them with snapshot.foreach().
  • once we've added all friends to the list, we call setstate to inform react of them.

in the comments you indicate you want all friends lists combined, which you can do with:

let eventsref = firebase.database().ref('events');
eventref.once('value').then((snapshot) =>{
  let allfriendlist = [];
  snapshot.foreach((eventsnapshot) => {
    eventsnapshot.child('friends').foreach((friendsnapshot) => {
      let data = friendsnapshot.val();
      alluserlist.push(data);
    });
  });
  this.setstate({allfriendlist: allfriendlist});
});

but i highly recommend changing/augmenting your data model for this use-case. this code may work, but reads way more data than is needed. it also may be reading duplicate friends, if the same friend is present in more events. if you want a global list of friends, i'd store precisely that in the database: a list of users, with possibly the event ids of the events they're friends with.

score:0

personal preference, using the [key] approach works well for custom key names.

for instance, data.[key].name will yield your results if you know the key.

if you don't know that key (lrjsl...) you can iterate over the friends object:

for (var key in data) {
    data[key].name //will be shabnam
}

score:2

you can just do the full path in the ref:

firebase.database().ref('/events/friends/whatever-key')
    .once('value').then((snapshot) =>{
        /// whatever code
    });

Related Query

More Query from same tag