Joe Privett Joe Privett - 3 months ago 34
React JSX Question

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

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

Answer

$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