1

I'm trying to write a simple ToDo app.

Clicking on TodoItem should remove a item from state but when I do this I'm getting a TypeError: this.state is undefined. I don't know what is wrong.

My code looks like this:

---- App.js ----

import React from "react";
import TodoItem from "./components/TodoItem";

class App extends React.Component {
  state = {
    items: {
      item1: { text: "Nazwa item1", isDone: false },
      item2: { text: "Nazwa item2", isDone: false },
      item3: { text: "Nazwa item3", isDone: false },
      item4: { text: "Nazwa item4", isDone: false }
    }
  };

  removeItem(key) {
    const items = { ...this.state.items }; // TypeError: this.state is undefined
    console.log(items);
  }

  render() {
    return (
      <React.Fragment>
        <ul>
          {Object.keys(this.state.items).map(key => (
            <TodoItem
              removeItem={this.removeItem}
              index={key}
              key={key}
              item={this.state.items[key]}
            />
          ))}
        </ul>
      </React.Fragment>
    );
  }
}

export default App;

---- TodoItem.js ----

import React from "react";

const TodoItem = props => {
    return (
        <li onClick={() => props.removeItem(props.index)}>
            {props.item.text}
            {props.item.isDone ? "zrobione" : "niezrobione"}
        </li>
    );
};

export default TodoItem;
Konrados
  • 508
  • 1
  • 5
  • 13

1 Answers1

1

The issue is that this is bound to your function and not to the class.

To prevent that you can use an arrow function to keep the binding of this to the class, or calling .bind method

That should make it work:

 removeItem = (key) => {
    const items = { ...this.state.items };
    console.log(items);
  }

or that:

removeItem={this.removeItem.bind(this)}

Here is a more in-depth article

Kevin Amiranoff
  • 13,440
  • 11
  • 59
  • 90
  • 1
    Maybe, if they have the right transpiling setup (which they probably do). But a good answer says **what** it changed, and **why**, and **how** it works. (And probably removes the hopefully-now-erroneous comment.) In any case, this is an opt-repeated duplicate well covered by previous answers. – T.J. Crowder Jul 22 '18 at 16:51
  • 1
    Changing to arrow function solved a problem. – Konrados Jul 22 '18 at 17:02
  • @T.J.Crowder I am a fool for these points. :( – Kevin Amiranoff Jul 22 '18 at 17:12