5

I have tried to do this:

 const rowObj = {key: value};
    const rowIndex = 2;

    this.setState({ 
          data: update(this.state.data, 
              { [rowIndex] : { $push : [rowObj] } }
          ) 
    })

But, It throw error like this:

Uncaught Error: update(): expected target of $push to be an array; got undefined.
Piyush k
  • 297
  • 3
  • 14
Sagar Chavada
  • 5,169
  • 7
  • 40
  • 67

3 Answers3

2

Try like this

const rowArray = [{key: value},{key: value},{key: value}];
const obj = {key: value}
const rowIndex = 2;
rowArray.splice(rowIndex, 0, obj);
this.setState({ data: update(this.state.data,{rowArray : {$set : rowArray}} ) });
1

Since you want to push to an array i.e data, you would not want to specify the index and write it like

const rowObj = {key: value};

this.setState({ 
      data: update(this.state.data, 
           { $push : [rowObj] } 
      ) 
})

or else if you want to set a value to a particular index in the array, you should use $set

const rowObj = {key: value};
const rowIndex = 2;

this.setState({ 
      data: update(this.state.data, 
          { [rowIndex] : { $set : rowObj } }
      ) 
})
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
  • but in my case i need to insert new row on particular index.. i cant use $set.. is it possible with push? – Sagar Chavada Aug 16 '18 at 05:51
  • any other option without using looping? bcz my row data length is about 5000+ – Sagar Chavada Aug 16 '18 at 05:55
  • Since this.state.data[rowIndex] is undefined and not an arrary before you push, it will give you an error and why can't you use set – Shubham Khatri Aug 16 '18 at 05:55
  • [{id: 1, rowId: "rw153431859379599d449", sequence: 1, cl1534318588226572647: "asd", cl15343185882290af581: "test"}, {id: 2, rowId: "rw1534318593795aea780", sequence: 2, cl1534318588226572647: null, cl15343185882290af581: null}, {id: 16, rowId: "rw1534396933085ae919c", sequence: 3, cl1534318588226572647: null, cl15343185882290af581: null}] – Sagar Chavada Aug 16 '18 at 06:03
  • @SagarChavada, its visible from your sample data that this.state.data[rowIndex] is not an array, but an object and push property is not supported on object, you should instead use $set or $merge if you want to merge the properties – Shubham Khatri Aug 16 '18 at 06:23
0

Based on this answer here's a version that uses immutability helper itself

const rowArray = [{
  key: value
}, {
  key: value
}, {
  key: value
}];
const obj = {
  key: value
}
const rowIndex = 2;
this.setState({
  data: update(this.state.data, {
    rowArray: {
      $splice: [
        [rowIndex, 0, obj]
      ]
    }
  })
});
Charles-Eugene Loubao
  • 1,080
  • 2
  • 12
  • 22