Reputation: 962
I tried to call a function in set time inter val for every 5 seconds but i throws errors in TypeError: this.intialState is not a function
componentDidMount() {
this.intialState();
setInterval(this.changeSelection,5000);
}
changeSelection(){
this.intialState();
}
TypeError: this.intialState is not a function
Upvotes: 0
Views: 68
Reputation: 3359
Updated 5-second countdown using class Clock extends Component
import React, { Component } from 'react';
class Clock extends Component {
constructor(props){
super(props);
this.state = {currentCount: 10}
}
timer() {
this.setState({
currentCount: this.state.currentCount - 1
})
if(this.state.currentCount < 1) {
clearInterval(this.intervalId);
}
}
componentDidMount() {
this.intervalId = setInterval(this.timer.bind(this), 1000);
}
componentWillUnmount(){
clearInterval(this.intervalId);
}
render() {
return(
<div>{this.state.currentCount}</div>
);
}
}
export default Clock;
Upvotes: 1
Reputation: 222
The problem is that your function 'changeSelection' does not have access to 'this'.
There are two easy ways to solve this issue:
this.changeSelection = this.changeSelection.bind()
changeSelection = () => {};
Click here to see more ways to do binding
You can read more about why we need binding why and how to bind
Upvotes: 0
Reputation: 4568
this
loses its context inside functions. You can bind changeSelection
in the constructor
constructor() {
super();
this.changeSelection = this.changeSelection.bind(this);
setInterval(this.changeSelection, 500);
}
or make it a fat arrow function since these functions don't have their own this
context and will take the parent's
changeSelection = () => {
// code here
}
Upvotes: 0
Reputation: 645
An arrow
function expression is a syntactically compact alternative to a regular function expression, although without its own bindings to the this
componentDidMount() {
this.intialState();
setInterval(this.changeSelection,5000);
}
changeSelection = () => {
this.intialState();
}
Upvotes: 0