Ad

React And Firebase: Return Single Item

- 1 answer

I'm trying to return a single item from Firebase into my ReactJS app.

Why does this code not work?

renderItem: function() {
  var id = "-K7rCis1K3wyVnDbLzs3";
  var child = <h2>{this.state.items[id].title}</h2>
  return child;
},

In the console it says: Cannot read property 'title' of undefined

I can return a single item with all the data in it, but not just the title. What would the correct syntax be for this?

Thanks :)

* EDIT * Here's the complete code

var HelloWorld = React.createClass({
    mixins: [ReactFireMixin],
    getInitialState: function() {
      return {
        items: {},
        loaded: false
      };
    },
    componentWillMount: function() {
      fb = new Firebase("firebasepath");
      this.bindAsObject(fb, "items");
      fb.on("value", this.handleDataLoaded);
    },

    render: function() {
      return <div>
        {this.renderItem()}
      </div>
    },
    renderItem: function() {
      var id = "-K7rCis1K3wyVnDbLzs3";
      var child = <h2>{this.state.items[id].title}</h2>
      return child;
    },

    handleDataLoaded: function() {
      this.setState({loaded: true});
    }

  var element = React.createElement(HelloWorld);
  React.render(element, document.body);
Ad

Answer

Thanks for the answer. I found a solution that fits into my code, here goes:

renderItem: function() {
      var id = "-K7rCis1K3wyVnDbLzs3";
      var item = this.state.items[id];
      if(item) {
        return <h2>{item.title}</h2>
      } else {
        <div>Loading..</div>
      }
    },

The reason why it wasn't showing, is that my component is rendering once before the data has actually loaded.

Ad
source: stackoverflow.com
Ad