Daniel Zuzevich Daniel Zuzevich - 4 months ago 11
React JSX Question

React + Firebase undefined using click event

Hopefully this is a quick fix. Basically, I have set onClick listeners on a few elements of a child component, and when they are clicked, it runs a function from the main component. Everything works good, up until we hit a specific line in the call to the firebase database, where I get issues of undefined. I have included comments to the code below so you know exactly what's going on.

getDataName(event) {
var title;
var that = this;
// Grabs data name attribute from element clicked
var grabIdentifier = event.target.getAttribute('data-name');
console.log(grabIdentifier); // prints "cruise"

// Call to firebase
var greeting = database.ref('events/travel');
greeting.once('value').then(function(snapshot) {
console.log(grabIdentifier); // prints "cruise"

// Set title to value of the "cruise" key.
title = snapshot.val().grabIdentifier;
console.log(title); // prints "undefined" =(

greeting : title

The idea here is to set the state to the text that is stored as a value under the key of "cruise" in the firebase db. Stumped!

It also might help to mention that if I rewrite the line below, and actually put the word, "cruise" there, it works...which is strange. See below,

title = snapshot.val().cruise;


You are trying to access the property called grabIdentifier you need to use bracket notation to access the property name that grabIdentifier is referencing

title = snapshot.val()[grabIdentifier]

for more information on property accessors see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors