E
E
embiid2020-06-23 13:55:14
JavaScript
embiid, 2020-06-23 13:55:14

Why does an error occur when deleting an entry from a todo?

Parent with delete function:

class App extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      items: [],
      currentItem: {
        text: '',
        key: '',
      }
    }

    this.addItem = this.addItem.bind(this)
    this.deleteItem = this.addItem.bind(this)
    this.handleInput = this.handleInput.bind(this)
  }

deleteItem(key) {
    const filteredItems= this.state.items.filter(item => item.key !== key)
    this.setState({
      items: filteredItems
    })
  }
render() {
    return (
      <div className="App">
        <header>
          <form id="goalForm">
            <input type="text" placeholder="Enter your main goal"
                   value={ this.state.currentItem.text }
                   onChange={ this.handleInput }>
            </input>
            <button type="submit" onClick={ this.addItem }>Add</button>
          </form>
        </header>

        <ListItems items      = { this.state.items }
                   deleteItem = { this.deleteItem }
        />
      </div>
    )


Well, the enumeration of "tasks" themselves:
function ListItems(props) {
    const items = props.items
    const listItems = items.map(item => {
        return (
            <div className="list" key = { item.key }>
                <div className="goal">
                    <p>{ item.text }</p>
                    <span>
                        <FontAwesomeIcon className="faicons" icon={ faTrash }
                            onClick={() => {
                                    props.deleteItem(item.key)
                                }
                            }
                        />
                    </span>
                </div>
            </div>
        )
    })

    return (
        <div>{ listItems }</div>
    )
}


I get an error like this:
5ef1dfc8c4c06497167517.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2020-06-23
@embiid

this.deleteItem = this.addItem.bind(this)

So add or delete? You already decide.
Better yet, use the arrow function syntax when declaring methods, and then you won’t need to manually bind the context:
class App extends React.Component {
  addItem = e => {
    ...
  }

  deleteItem = key => {
    ...
  }
  ...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question