How can I access nested data in Firebase with React?

- 1 answer

Ad

I am working on building a simple app with React and Firebase - a way to manage income and expenditure, and my Firebase is set up with the following structure:

"cashbook" : {
  "expenditure" : {
    "expenditure-1" : {
      "amount" : "500",
      "category" : "insurance",
      "date" : "date",
      "name" : "Life Insurance",
      "type" : "recurring"
    }
  },
  "income" : {
    "salary" : {
      "amount" : "500",
      "category" : "salary",
      "date" : "date",
      "type" : "recurring"
    }
  }
}

I have React set up and working perfectly with just the expenditure, using Re-base:

componentDidMount: function() {
    // Two way data binding
    base.syncState('cashbook/expenditure', {
      context: this,
      state: 'expenditure'
    });
  },

I can then reference using: this.state.expenditure

However, when I try to expand the app to access the Income data, things go pear shaped. I amended the componentdidmount to:

componentDidMount: function() {
    // Two way data binding
    base.syncState('cashbook', {
      context: this,
      state: 'cashbook'
    });
  },

And try to access with this.state.cashbook.expenditure and this.state.cashbook.income, but no joy, I get the error: Uncaught TypeError: Cannot read property 'expenditure' of undefined.

Not quite sure what to try, any pointers would be divine brown.

Thanks in advance :)

Ad

Answer

Ad

Turns out I was being a moron :)

I just needed to use syncstate on cashbook instead of cashbook/expenditure and call this.state.cashbook.expenditure.

Ad
source: stackoverflow.com
Ad