Skip to content
Advertisement

I can’t figure out how to work with the object returned by Firebase get query

I’m building a React Native app with Expo and integrating Firebase (real time database) which I know has some limitations (https://docs.expo.dev/guides/using-firebase/). I’m trying to get a snapshot of the data using await get(query(... and have successfully done so, but I can’t figure out exactly what I’m working with. When I console.log it I get this:

Object {
  "key1": value1,
  "key2": value2,
}

I was trying to return an array of the keys using Object.keys() but it returns this:

Array [
  "_node",
  "ref",
  "_index",
]

This doesn’t line up with the examples of Object.keys() I’m seeing on the internet which makes me think this isn’t a JSON object like I thought it was. I’ve tried poking around a good bit with some other stuff but can’t figure it out. The problem is, when I use typeof on the object, it simply returns ‘object’ which is a little too vague for me to take to the google machine.

The following is a representation of my code. Thanks for your help.

import { initializeApp } from 'firebase/app';
import { get, getDatabase, query, ref } from 'firebase/database';

const firebaseConfig = {
    databaseURL: '<myURL>',
    projectId: '<myID>',
};
const app = initializeApp(firebaseConfig);

export default async function myFunction() {
    const db = getDatabase(app);
    const readReference = ref(db, '/<I am only reading a piece of the data>')
    const existingData = await get(query(readReference))
    const dataKeys = Object.keys(existingData)
    console.log(dataKeys)
    console.log(existingData)
    console.log(typeof existingData)
}

Advertisement

Answer

What you get back from Firebase is known as a DataSnapshot, and contains the JSON of the location you read, and some more metadata.

If you just want to get the JSON value of the snapshot, use snapshot.val() as shown in the Expo documentation for Storing Data and Receiving Updates.

Something like:

const existingData = await get(query(readReference))
const dataKeys = Object.keys(existingData.val())
console.log(dataKeys)
console.log(existingData.val())
console.log(typeof existingData.val())
Advertisement