-1

I'm creating a simple todo app in React. I have three components. The 'Items' component is in charge of displaying and deleting items from the list. When I click on the 'Done' button next to an item, the index of the item is getting logged to the console but not getting deleted. My code is as follows,

//App.js
export default class App extends React.Component{
  constructor(props){
    super(props);
    this.state = {list:[]}
    this.addItem = this.addItem.bind(this)
    this.handleRemove = this.handleRemove.bind(this)
  }

  addItem(val) {
    let updated = [...this.state.list, val];
    this.setState({ list: updated });
  }
  
  handleRemove(key){ 
    const list = [...this.state.list]; 
  
    const updateList = list.filter(item => item.id !== key); 
  
    this.setState({ 
      list:updateList, 
    }); 
  
  } 

  render(){
    return (
    <div className="App">
      <Title itemCount={this.state.list.length}></Title>
      <Add addItem={this.addItem}></Add>
      <Items items={this.state.list} remove={this.handleRemove}></Items>
    </div>
  );
  }
  
}

//Items.js
const Items = ({items, remove}) => {
    return(
        <div className="Items">
            <ul>{items.map((item, index) => 
                <li key={index}>
                    {item}
                    <button onClick={() => remove(index)}>Done</button>
                </li>
                )}
            </ul>
        </div>
    );
}

What can I do to fix this? Thanks in advance!

9
  • what's the content of the items? Can you share the data structure? Commented Oct 3, 2020 at 12:55
  • 1
    Check for string and number comparison. There is a possibility that a string is being compared with a number in filter function Commented Oct 3, 2020 at 12:58
  • 2
    Are you sure that the item.id and key have the same value and data type? And did you console.log the updateList? Commented Oct 3, 2020 at 13:00
  • 1
    If I understand correctly, you're trying to delete using the index, you can try something like const updateList = list.filter((_, i) => i !== key) - while using remove(index) Commented Oct 3, 2020 at 13:18
  • 1
    @Nick Parsons I just tried this. It works! Thanks. Commented Oct 3, 2020 at 13:20

1 Answer 1

2

You are not passing the id to the callback in Items component

<button onClick={() => remove(index)}>Done</button>

should be

<button onClick={() => remove(item.id)}>Done</button>
Sign up to request clarification or add additional context in comments.

1 Comment

This is deleting the items but all of them. How do I get them to delete the item I have clicked?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.