0

Getting undefined value of handleClick() in countStat(). What is the exact problem happening right there? What should I change in the code?

class Widget extends Component {
  state = {
    good: 0,
    neutral: 0,
    bad: 0
  };

  handleClick(event) {
    const id = event.target.id;
    return id;
  }

  countStat(id, e) {
    id = this.handleClick(e);
    if (id === "good") {
      this.setState(prevState => ({
        good: prevState.good + 1
      }));
    }
  }
  render() {
    return (
      <li className={classes.Button}>
        <button onClick={this.countStat} id="good">
          Good
        </button>
      </li>
    );
  }
}

export default Widget;
Raghul SK
  • 1,256
  • 5
  • 22
  • 30
ElMuchacho
  • 300
  • 1
  • 12

2 Answers2

3

To make it work you can do:

<button onClick={(event) => this.countStat('good', event)} id="good">Good</button>
kadash
  • 282
  • 1
  • 11
2

Couple issues

  1. this isn't bound to countStat nor handleClick
  2. countStat function signature doesn't match usage

Solution

  1. Bind this to countStat in a constructor, or use an arrow function, and remove handleClick since it isn't used/necessary
  2. Update countStat function to get id from event.target

Updated component

class Widget extends Component {
  state = {
    good: 0,
    neutral: 0,
    bad: 0
  };

  countStat = e => {
    const { id } = e.target;
    if (id === "good") {
      this.setState(prevState => ({
        good: prevState.good + 1
      }));
    }
  }

  render() {
    return (
      <li className={classes.Button}>
        <button onClick={this.countStat} id="good">
          Good
        </button>
      </li>
    );
  }
}
Drew Reese
  • 165,259
  • 14
  • 153
  • 181
  • Thank you, sir! but i still don't understand why this isn't bound to countStat nor handleClick... – ElMuchacho Jul 15 '20 at 07:32
  • @ElMuchacho Maybe this explain? https://stackoverflow.com/questions/34361379/are-arrow-functions-and-functions-equivalent-exchangeable TL;DR though is that functions don't inherit the `this` of the caller, the class component in this case, so they have to be manually bound to `this` of the component. Arrow function notation does this for you. – Drew Reese Jul 15 '20 at 07:36