'Push new object at specific index using immutability helper

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.


Solution 1:[1]

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}} ) });

Solution 2:[2]

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 } }
      ) 
})

Solution 3:[3]

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]
      ]
    }
  })
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jay Jariwala
Solution 2 Shubham Khatri
Solution 3 Charles-Eugene Loubao