K
K
Konstantin2020-07-06 20:56:23
React
Konstantin, 2020-07-06 20:56:23

Removing an element from the UI in React. Do I need to pass the previous state to setState?

How would be more correct? So:

deleteItem = (id) => {
    this.setState(({todoData}) => {
      const idx = todoData.findIndex((el) => el.id === id);
      const newArray = [
        ...todoData.slice(0, idx),
        ...todoData.slice(idx + 1)
      ]

      return {
        todoData: newArray
      }
    })
  }


Or like this:

deleteItem = (id) => {
    const todo = this.state.todoData.filter((todo) => {
      return todo.id !== id;
    });

    this.setState({
      todoData: todo,
    });
  };

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
i1yas, 2020-07-06
@jcricket

newArray = [
 ...todoData.slice(0, idx),
 ...todoData.slice(idx + 1)
]

Well, this is how I would not advise concatenating arrays, it's better:
todoData.slice(0, idx).concat(todoData.slice(idx + 1))

Well, this option is most likely saving on matches, it is better to use a filter if you do not operate with some incredible amount of data on the client (which is already strange).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question