Push items into empty State array of objects

Paras Watts Source

I am trying to push new items into State array of objects, facing some problem. Below is my code. I am sure I am going something wrong

constructor(props) {
  this.state = {
    bill: []

componentWillReceiveProps(nextProps, nextState) {
  if (nextProps.bills !== this.props.bills) {
    let billsObj = nextProps.bills
    billsObj.map((billsObj) => {
      var joined = this.state.bill.concat({billId:billsObj.id,checked:false});
      console.log(joined, "joined", this.state.bill)
        bill: [...this.state.bill, ...joined]
      }, () => {
        console.log(this.state.bill, billsObj.id)

In componentWillReceiverProps I am getting the array and then mapping it to push values into state array, But in the end I am only getting a single value in the array , but props array has 11 values and I am only getting single value in my state array. Hope to get some help.



answered 3 months ago Tholle #1

You need to account for previous state if you are updating a piece of state that is derived from the current state, which is explained in detail here. This is why your multiple calls to setState just end up with the last bill in your state array.

It will work as expected if you keep your bills in an intermediary array, and just setState once when you are done:

componentWillReceiveProps(nextProps, nextState) {
  if (nextProps.bills !== this.props.bills) {
    const bill = nextProps.bills.map(bill => {
      return { billId: bill.id, checked: false };

    this.setState({ bill });

comments powered by Disqus