Eric
Eric

Reputation: 1034

React Uncaught TypeError: _this2.setState is not a function

I've checked on stackoverflow for this error and the only results i've been getting is that the functions needs to be binded with this. but i have done so in my code and the error still persists. I cant figure out why this is happening. full code on CodePen and a shorted copy below

class MainComponent extends React.Component{
  constructor(props) {
    super(props);
    this.setOperand = this.setOperand.bind(this);
    this.calculate = this.calculate.bind(this);
    this.updateValue = this.updateValue.bind(this);
    this.state = {
      currentValue: 0,
      secondValue: 0,
      operand: null,
      isNewNum: false
    };
  }

  setOperand = (value) => {
    //set data from input
  };

  calculate = () => {
    //math stuff
    this.setState = ({
      currentValue: result,
      isNewNum: false
    });
  };

  updateValue = (value) => {
    if(!this.state.isNewNum){ //first Number
      var newNum = "";
      //set values
      this.setState({
        currentValue: newNum
      });
    } else {
      var newNum2 = "";
      //set values
      this.setState({
        secondValue: newNum2
      });
    }
  };

  render(){
    return(
      <div id="main">
        <p>isNewNum = {`${this.state.isNewNum}`}</p>

        {this.state.isNewNum ?  <Display display ={this.state.secondValue}/> : <Display display ={this.state.currentValue}/>}
        <div>
          <Buttons value={1} onClick={this.updateValue}/>
          ...
          <Buttons value={'+'} onClick={this.setOperand}/>
        </div>
      </div>
    )
  };
}


ReactDOM.render(<MainComponent />, document.getElementById("root"));

Upvotes: 2

Views: 2079

Answers (2)

Dimitar Christoff
Dimitar Christoff

Reputation: 26165

er.

you actually create a local copy of the setState property of your instance in the calculate method, severing the proto chain to React.Component as it starts being resolved locally.

this is the error:

this.setState = ({
  currentValue: result,
  isNewNum: false
});

that extra = is an assignment. any subsequent calls that do setState would fail

Upvotes: 2

Tyler Sebastian
Tyler Sebastian

Reputation: 9468

You don't need to rebind the callbacks in the constructor as arrow function inherit the context of the enclosing class (in this case the component).

Upvotes: 0

Related Questions