I
I
Igor Braduloff2019-12-26 23:27:16
React
Igor Braduloff, 2019-12-26 23:27:16

Why item is not removed?

Good afternoon! Tell me why item is not removed, but added?

class App extends Component {
  state = {
    todoData:[
      { label: 'Drink Coffee', important: false, id: 1 },
      { label: 'Make Awesome App', important: true, id: 2 },
      { label: 'Have a lunch', important: false, id: 3 }
    ]
  }
  
  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
      }
    })
  }
  render(){		
    return (
    <div className="todo-app">
      <AppHeader toDo={1} done={3} />
      <div className="top-panel d-flex">
        <SearchPanel />
        <ItemStatusFilter />
      </div>
      <TodoList todos={this.state.todoData} onDeleted={this.deleteItem}  />
    </div>
  );
  }  
}
ReactDOM.render(<App />,
  document.getElementById('root'));

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2019-12-27
@0xD34F

why item is not removed, but added?

Added E tsya - how is it? I would believe in "adding Yu tsya" - if a non-existent id is passed to deleteItem, then the element index will be -1, and the new array will be a copy of the original without the last element ( ) plus a full copy ( ). In general, deletion is not done this way, there is a filter:slice(0, -1)slice(0)
deleteItem = id => {
  this.setState(({ todoData }) => ({
    todoData: todoData.filter(n => n.id !== id),
  }));
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question