Search code examples
reactjsreact-nativeimmutability-helper

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

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