sadiq ali
sadiq ali

Reputation: 77

Get children specific value and update when there is a change Firebase v9

I have this database. I would like to get only the values highlighted red. When there is a new child with same value profile_picture:, i would like to update the list as well.

enter image description here

I manage to get all the values but i still can't figure out how to get only profile_picture: value from every child.

    // Initialize Firebase
    const app = initializeApp(firebaseConfig);
    const db = getDatabase();
    const email = ref(db, 'users/');
    onValue(email, (snapshot) => {
        console.log(snapshot.val())
    })

OUTPUT

[
null,
{
    "email": "Test_1_Email",
    "profile_picture": "Test_1_URL",
    "username": "Test_1"
},
{
    "email": "Test_2_Email",
    "profile_picture": "Test_2_URL",
    "username": "Test_2"
}
]

Upvotes: 0

Views: 472

Answers (1)

Dharmaraj
Dharmaraj

Reputation: 50830

That cannot be done by a single listener. ref(db, 'users/') will return the whole /users node. If you just want to listen for profile_picture then you'll have to add a listener for every user's profile_picture like this:

const userIds = ["u1", "u2"]

userIds.forEach(user => {
  const email = ref(db, 'users/' + user);
  onValue(email, (snapshot) => {
    console.log(snapshot.val())
  })
})

I had hard-coded the UIDs here for example but you'll need to know the user IDs beforehand to use this.

Alternatively, you can just store the frequently accessed information such as user name and picture in a separate node.

Upvotes: 1

Related Questions