Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React addons update - how to insert an object into an array of objects?

Tags:

reactjs

I have an array of objects represented by this.state.blocks . How do I insert a new object into this array at position pos? This is what i have so far, but I am getting the error

Error: update(): expected target of $push to be an array; got [object Object].

let newBlocks = update(this.state, {
    blocks: {
        [pos] : {$push: [obj]}
    }
});
this.setState({
    blocks: newBlocks
});
like image 603
JoeTidee Avatar asked Dec 06 '25 07:12

JoeTidee


1 Answers

$push appends element(s) to the end of the array and you need $splice here:

this.setState({
  blocks: update(this.state.blocks, {$splice: [[pos, 0, obj]]})
})

will insert obj into this.state.blocks at index specified by pos (deleting 0 items first).splice works according to the spec:

startIndex: index at which to start changing the array (with origin 0). If greater than the length of the array, actual starting index will be set to the length of the array. If negative, will begin that many elements from the end.

so it will work fine as long as the startIndex is within the length of the array

like image 94
Igorsvee Avatar answered Dec 07 '25 22:12

Igorsvee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!