Md. Robi Ullah
Md. Robi Ullah

Reputation: 2172

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

Upvotes: 0

Views: 257

Answers (1)

Jerome De Wulf
Jerome De Wulf

Reputation: 66

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

Upvotes: 5

Related Questions