Reputation: 15293
I am trying to update my strikes, but while i do, getting error as
Cannot read property 'strikes' of undefined
What is the error with my code? any one help me to figure out?
here is my class:
Cannot read property 'strikes' of undefined
class LightningCounter extends React.Component {
constructor(props) {
super(props);
this.state = {
strikes: 0
};
}
timerTick() {
this.setState({
strikes: this.state.strikes + 100 //getting red underline here
});
}
componentDidMount() {
setInterval(this.timerTick, 1000);
}
render() {
return <h1>{this.state.strikes}</h1>;
}
}
Upvotes: 0
Views: 49
Reputation: 309
That is because of the context of this keyword, the this timertick doesnt know that it belongs to class, it is pointing to itself as function.
use arrow function which is a ES6 standard now like this
timerTick = () => {
`enter code here`
}
or in the constructor bind the function this way
this.timerTick = this.timerTick.bind(this);
Check the documentation of bind to get more clarity
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind
Hope it works
Upvotes: 3