I need to read the value of the snapshot.val() response. The structure of my Firebase Realtime Database looks like this:
example-default-rtdb
+ 1234567
++ abcdefg
+++ foo: "bar"
Firebase:
const db = firebase.database()
const ref = db.ref('1234567/')
ref.limitToLast(1).on(
'value',
snapshot => {
const response = snapshot.val()
const message = response.foo
},
errorObject => {
console.log("error")
}
)
response.foo returns undefined instead of bar. I tried JSON.parse and JSON.stringify - they all return undefined.
This the output if I use const message = JSON.stringify(response, null, ' ')
{
"123456": {
"foo": "bar"
}
}
How to access the value of foo?
It sounds like you don't know the abcdefg, in which case you can use forEach to loop over all the child nodes of snapshot:
const db = firebase.database()
const ref = db.ref('1234567/')
ref.limitToLast(1).on(
'value',
snapshot => {
snapshot.forEach((child) => {
console.log(child.key, child.val(), child.val().foo)
}
},
errorObject => {
console.log("error")
}
)