Lee
Lee

Reputation: 224

can anyone tell me why i am unable to delete an item from the todo list?

Im having issues with react todo list.

When submitted the list item appears fine.

I should then be able to delete this be clicking on the item,however nothing happens. As soon as i try to add another item the pages refreshes and all items are removed?

console log just shows

[object object]


App

import React, { Component } from 'react';
import './App.css';
import TodoItem from './TodoItem';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      items: []
    };
    this.addItems = this.addItems.bind(this);
    this.deleteItem = this.deleteItem.bind(this);
  }

  addItems(e) {
    if (this._inputElement !== '') {
      let newItem = {
        text: this._inputElement.value,
        key: Date.now()
      };
      this.setState(prevState => {
        return {
          items: prevState.items.concat(newItem)
        };
      });
    }
    this._inputElement.value = '';
    e.preventDefault();
  }

  deleteItem(key) {
    console.log('key is' + key);
    console.log('itesm as' + this.state.items);
    var filteredItems = this.state.items.filter(function(item) {
      return item.key !== key;
    });
    this.setState = {
      items: filteredItems
    };
  }

  render() {
    return (
      <div className="app">
        <h2> things to do</h2>
        <div className="form-inline">
          <div className="header">
            <form onSubmit={this.addItems}>
              <input
                ref={a => (this._inputElement = a)}
                placeholder="enter task"
              />
              <button type="submit">add</button>
            </form>
          </div>
        </div>
        <TodoItem entries={this.state.items} delete={this.deleteItem} />
      </div>
    );
  }
}
export default App;

todoItem

import React, { Component } from 'react';

//search bar
class TodoItem extends Component {
  constructor(props) {
    super(props);
    this.createTasks = this.createTasks.bind(this);
  }
  createTasks(item) {
    return (
      <li onClick={() => this.delete(item.key)} key={item.key}>
        {item.text}
      </li>
    );
  }
  delete(key) {
    console.log('key is ' + key);
    this.props.delete(key);
  }
  render() {
    let todoEntries = this.props.entries;
    let listItems = todoEntries.map(this.createTasks);
    return <ul className="theList">{listItems}</ul>;
  }
}

export default TodoItem;

Upvotes: 1

Views: 70

Answers (1)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196246

You are assigning to setState instead of using it as a method that it is

Change

this.setState = {
  items: filteredItems
};

to

this.setState({
  items: filteredItems
});

And that is also the reason it will reload the app, as you have overwritten the setState method you should be getting an error that setState is not a function and it would crash the app.

Upvotes: 3

Related Questions