11

I'm attempting to add an object at a specific point in my 'data' array which is this components state. The following isn't working, the array simply gets emptied.

addNewBulletAfterActive = () => {
    const array = this.state.data;
    const newBulletPoint = {
        id: this.state.data.length += 1,
        title: 'Click to add'
    };
    const newData = array.splice(this.state.activeBulletPointId, 0, newBulletPoint);
    this.setState({
        data: newData
    });
}

The idea is that if I have a list of 10 bullet points, the user can click on the 4th bullet point and press enter to add a new bullet point directly after. I've not had any issues adding items to the end of the array but it looks like .splice is causing issues.

3 Answers 3

29

I believe this should do what you're after.

function addAfter(array, index, newItem) {
    return [
        ...array.slice(0, index),
        newItem,
        ...array.slice(index)
    ];
}

This function returns a new array with a new item inserted in the middle. It doesn't mutate your original array and so will play nicely with component's state and Redux.

You can then assign the output from this function to your state.

Sign up to request clarification or add additional context in comments.

1 Comment

I think this answer should be the one accepted
12

splice returns spliced items (which is empty since you splice 0 items) and mutates original array.

const newData = array.slice(0); // copy

newData.splice(this.state.activeBulletPointId, 0, newBulletPoint);

this.setState({
    data: newData
});

4 Comments

splice will mutate state which is generally a bad practice
@Valentin I've added slice before splice :)
So far this is the only answer that actually explains why the OP's code didn't work.
This is exactly what I was after. Thanks @YuryTarabanko
-1

I think this could be an easier and faster method to do this

/*Just plain JS*/
function AddAfter(array, newObject){
    array.unshift(newObject);
  }
  
/*In react If updating state*/
var _prev = this.state.your_array; //getting the current value for the state object
var newInfo = {id: 1, more: 'This is a new object'};
_prev.unshift(newInfo);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.