Reputation: 419
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?
Upvotes: 0
Views: 1407
Reputation: 1912
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.
Upvotes: 1