0

Hey I am trying to delete an item inside the component. I am getting this table from antd Design

<div>
  <button onClick={this.createItem}>Create Item</button>
  <CSSTransition timeout={500} classNames="fade">
    <Table
      columns={[
        {
          title: "ID",
          dataIndex: "id",
          key: "id",
        },
        {
          title: "Name",
          dataIndex: "name",
          key: "name",
          render: (text) => <a>{text}</a>,
        },
        {
          title: "Action",
          key: "action",
          render: (text, record) => (
            <span>
              <a onClick={() => this.handleDelete(record.key)}>Delete</a>
              <a onClick={() => this.deleteItem(record.key)}>Delete</a>
            </span>
          ),
        },
      ]}
      dataSource={data}
    />
  </CSSTransition>
</div>;

From what I know Normally I write delete function like this.

constructor(props) {
    super(props);
    this.state = {
      items: [
        { id: uuidv4(), name: "Eggs", tags: "love", key: uuidv4() },
        { id: uuidv4(), name: "Milks", tags: "love", key: uuidv4() },
        { id: uuidv4(), name: "Streak", tags: "love", key: uuidv4() },
        { id: uuidv4(), name: "Water", tags: "love", key: uuidv4() },
      ],
      data : [],
    };
    this.createItem = this.createItem.bind(this);
    this.deleteItem = this.deleteItem.bind(this);
  }

deleteItem(e) {
    // console.log(e)
    this.setState((state) => {
      items: state.items.filter((item) => item.key !== e);
    })
  }

Buts its not working.

When I write it like handledelete the function is working.

 handleDelete = key => {
    // console.log(key)
    const items = [...this.state.items];
    console.log(items)
    this.setState({
      items: items.filter(item => item.key !== key),
    });
  };

So what is the difference between deleteItem and handleDelete

Utsav Patel
  • 2,789
  • 1
  • 16
  • 26

1 Answers1

3

In the first version, you need to return a new state object.

deleteItem(e) {
    // console.log(e)
    this.setState((state) => ({
      items: state.items.filter((item) => item.key !== e);
    }))
  }

Wrapping the object in parenthesis will implicitly return it.

  • This is a nasty bug: the syntax is perfectly legal, but the code _strangely_ does not work. That's because the leading "items:" figures as a label. The rest of the code produces no effect on the state. – Mario Vernari Apr 24 '20 at 06:17
  • Alternatively he could simply set the state directly `this.setState({ items: ... })` – slebetman Apr 24 '20 at 06:18