Search code examples
javascriptarraysreactjssplice

Why is my splice deleting all but the first instead of only the one specified?


For a given array, when I run the splice everything but the first entry is deleted. However I would expect only the selected entry to be deleted. I suspect this has something to do with how my i is set up but I'm not sure what the problem is.

removethisone = (i) => {this.setState(state=>({list: state.list.splice(i,1)}))}

    <ul>
    {this.state.list.map((entry, i)=><li key={i}><button onClick={this.removethisone}>{i+1}</button>{entry}</li>)}
    </ul>

Solution

  • The reason this is happening is because the Array.splice method returns the removed items from the array.

    You need to do something like this:

    removethisone = (i) => {
      this.setState(state => {
        const nextState = [ ...state.list ]
        nextState.splice(i, 1)
    
        return { list: nextList }
      })
    }
    

    For example, run the code below to see the ouput:

    // This is what your code does
    let numbers = [1, 2, 3, 4, 5];
    let removedNumbers = numbers.splice(2, 1)
    numbers = removedNumbers
    
    console.log(numbers);
    console.log(removedNumbers);