Search code examples
javascriptreact-nativesplice

I think Splice(remove) method works as exactly opposite of its actual work


I am expecting to only remove the given index in "deleteNumber" method . But It's doing exactly the opposite. It removes all indexes except given index.

Javascript code:

deleteNumber = (index) => {
    console.log("index: ", index);
    this.setState((state) => {
        const numbers = state.numbers.splice(index, 1);
        this.storeData('numbers', JSON.stringify(numbers));
        return(
        {
            numbers: numbers,
        }
        )
    })
}

enter image description here


Solution

  • Splice alters the given array and returns the elements it removed. Something like this will set state to the new (altered) array.

    deleteNumber = (index) => {
      let numbers = this.state.numbers;
      numbers.splice(index, 1);
      this.setState({
        numbers
      });
    }