0

So I am using React Native and firebase and I have a JSON tree in firebase that is structured like this

{"Message"
  {"-LCi0UViBvOn4eh9cqzW":
    {"contents":"hello",
     "timestamp":1526559275118}
  }
}

I am trying to retrieve the contents of the message and store it in an object, and for now just read that value to the console. Here is my code where I attempt this:

const firebaseApp = firebase.initializeApp(firebaseConfig);
let db = firebaseApp.database();
let ref = db.ref("/message");

Attempting the read:

 componentDidMount() {
     ref.on("value", function(snapshot) {
      var messageText = JSON.stringify(snapshot.val());
      console.log(messageText);
      var parsedMessage = JSON.parse(messageText);
      console.log(parsedMessage.contents);
     });
  }

The first console.log gives me the following results:

{"-LCi0UViBvOn4eh9cqzW":{"contents":"hello","timestamp":1526559275118}}

But the next one console.log where I try to read the specific data from the parsed object always outputs undefined.

What am I doing wrong that won't allow me to retrieve that specific data from my JSON tree?

1 Answer 1

1

When you do your second JSON.parse and then console.log the parsedMessage.contents, that is actually nested within the key "-LCi0UViBvOn4eh9cqzW" so you should do console.log(parsedMessage["-LCi0UViBvOn4eh9cqzW"].contents) as the contents key is within the value of the root element.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, that gave me the data I needed. The only problem now is I won't have access to that id unless I hard code it in, as it's a random id generated when I push the value into firebase. Is there a way to access that specific data without referencing that id, or maybe a way to get that id from the database and save it to a variable to then use as the index for the parsed message?
Hi, yes you could first do a Object.keys(parsedMessage) and that would show you what the top level keys are. It'd be simple (if you expect only one top level key) to get the first item in the array that Object.keys returns.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.