Dalibor
Dalibor

Reputation: 1572

React - Deleting rest of the array instead of just one item

Here's the link: https://codesandbox.io/s/heuristic-heisenberg-9cxb9

I have this method: deleteItem

This code:

  return {
    monsters: prevState.monsters
      .slice(0, deleteItemPosition)
      .concat(
        prevState.monsters.slice(
          deleteItemPosition + 1,
          prevState.monsters.length
        )
      )
  };

This is the code I use to remove an item from array on position deleteItemPosition, because I can't use monsters.splice(deleteItemPosition, 1) because of immutability.

So why does my monsters array get cut off from deleteItemPosition to the end? Try it yourself, entering some number 0-5 into "index to delete"

If I update line

let deleteItemPosition = this.state.deleteItemPosition;

and I hardcode it to, let say

let deleteItemPosition = 3;

Then I notice the item on position 3 gets removed, as I wanted.

Upvotes: 0

Views: 86

Answers (2)

Ramesh Reddy
Ramesh Reddy

Reputation: 10652

Your deleteItem function could be simplified like this, also makes sure that no state updates are skipped:

deleteItem = () => {
    this.setState(prevState => {
      return { monsters: prevState.monsters.filter((_, i) => i !== +prevState.deleteItemPosition)};
    })
};

The functional update is recommended as your new state(new monsters array) depends on the previous state.

Update:

You can use destructuring to avoid using prevState all the time. And you need to convert the deleteItemPosition to a number because the input's value is a string.

deleteItem = () => {
    this.setState(({monsters, deleteItemPosition}) => {
      return { monsters: monsters.filter((_, i) => i !== +deleteItemPosition)};
    })
  };

Upvotes: 1

Sajeeb Ahamed
Sajeeb Ahamed

Reputation: 6390

Just make a shallow copy of the monsters array, apply Array.prototype.splice method for deleting your item and return the copied monsters array.

const copyMonsters = [...prevState.monsters];
copyMonsters.splice(deleteItemPosition, 1);

return {
  monsters: copyMonsters
}

Put this code inside the setState function in your case.

Upvotes: 1

Related Questions