Removing item in Firebase with React, re-render returns item undefined

- 1 answer

Ad

I am building an app to learn React, and am using Firebase as my data storage. I have all the items in my firebase rendering out, and am trying to enable removal of individual items. However, when I try to remove, I get Uncaught TypeError: Cannot read property 'name' of null after clicking on the remove button, and it is referring to this line of code in the renderExpenditure function:

<strong>{details.name}</strong>, <strong>{h.formatPrice(details.amount)}</strong>, {details.category}, {details.type}, {details.date}

The state is set up as follows:

getInitialState: function() {
    return {
      cashbook: {
        expenditure: {},
        income: {}
      },
      totals: {},
      available: {}
    }
  }

And the functions which render out the items and try to remove them are as follows:

(Can anyone see what I am doing wrong, or is this too little code to work out what is going on?)

Thanks in advance.

Within App

render: function() {
    return(
      <div className="cashbook">
        <div className="expenditure">
          <ul className="items">
            {Object.keys(this.state.cashbook.expenditure).map(this.renderExpenditure)}
          </ul>
        </div>     

      </div>
    );
  }

renderExpenditure: function(key) {
    var details = this.state.cashbook.expenditure[key];
    return(
      <li className="item" key={key}>
        <strong>{details.name}</strong>, <strong>{h.formatPrice(details.amount)}</strong>, {details.category}, {details.type}, {details.date}
        <button className="remove-item" onClick={this.removeExpenditure.bind(null, key)}>Remove</button>
      </li>
    );
  },

removeExpenditure: function(key) {
    this.state.cashbook.expenditure[key] = null;
    this.setState({
      expenditure: this.state.cashbook.expenditure
    });
  },
Ad

Answer

Ad

You are setting the wrong value in setState. expenditure doesn't exist in the root state, so you must overwrite the parent that contains it. It should be:

this.state.cashbook.expenditure[key] = null;
this.setState({
  cashbook: this.state.cashbook
});
Ad
source: stackoverflow.com
Ad