I was making an app and had to fetch data from Realtime Database. I am getting the data in snapshot.val() like this
JavaScript
x
3
1
►{xz0ezxzrpkb:{…}}
2
▼xz0ezxzrpkb:{blood_group:"B+",cause:"Random Cause",created_on:"08-02-2022",email:"example@gmail.com",location:"Random Location",message:"Random Message",name:"Any_Name",phone_number:"+91 *********"}
3
And Now I want to access this data. When I am trying snapshot.val()[0].email and
snapshot.val().[0].email I am Getting
JavaScript
1
2
1
undefined (2)
2
So, I am working in React Native and this is the code
JavaScript
1
6
1
db.ref('/requests/').on('value', (snapshot) => {
2
console.log(snapshot.val())
3
console.log(snapshot.val()[0].email)
4
console.log(snapshot.val().[0].email)
5
});
6
The nodes of database are as follows:
Please help me out.
Advertisement
Answer
While the approach in Dharmaraj’s answer works, I recommend using Firebase’s built-in forEach
operation, since that ensures that you process the results in the same order the database returns them:
JavaScript
1
9
1
db.ref('/requests/').on('value', (snapshot) => {
2
snapshot.forEach((childSnapshot) => {
3
console.log(childSnapshot.key) // "xz0ezxzrpkb"
4
console.log(childSnapshot.val()) // {blood_group:"B+",cause:"Random Cause", ...
5
console.log(childSnapshot.val().email) // "example@gmail.com"
6
console.log(childSnapshot.child('email').val()) // "example@gmail.com"
7
})
8
})
9