Tom
Tom

Reputation: 6004

Access value of Firebase RTDB snapshot on value

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?

Upvotes: 0

Views: 342

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598847

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")
  }
)

Upvotes: 1

Related Questions