1

This is what I have:

In AddExpenseForm component:

some sample data:

  constructor(){
    super();
    this.state = {
      expenseItems: [{
          uid: '222',
          date: '10-10-2017',
          desc: 'desc1',
          amount: 'amount1'
        },{
          uid: '333',
          date: '01-09-2017',
          desc: 'desc1',
          amount: 'amount1'
        },{
          uid: '444',
          date: '06-05-2017',
          desc: 'desc1',
          amount: 'amount1'
        }
      ]
    }
  }

My addItem function:

addItem = (item) => {
  const currentState = {...this.state.expenseItems};
  const expenseItems = {currentState, ...item};
  this.setState({expenseItems});
}

then I'm passing it down to AddItemForm via addItem={this.addItem}

In AddItemForm component:

My onSubmit:

<Form onSubmit={(e) => this.createItem(e)}>

then createItem function:

  createItem(event) {
    event.preventDefault();
    this.props.addItem({
      uid: Date.now(),
      date: this.state.date,
      desc: this.state.desc,
      amount: this.state.amount
    });
  }

I'm iterating through expenseItems sample data and it shows up fine but when I try to add a new object (item) I get that error: this.state.expenseItems.map is not a function

I guess I'm doing smth wrong in my addItem?

karolis2017
  • 2,195
  • 8
  • 24
  • 49

1 Answers1

2

Your use of rest/spread operators isn't correct for what you're trying to do. Try this:

addItem = (item) => {
  const expenseItems = [...this.state.expenseItems, item];
  this.setState({expenseItems});
}

Edit: for reference, link to the Spread operator syntax

Thomas Hennes
  • 9,023
  • 3
  • 27
  • 36