Ian
Ian

Reputation: 285

react native setState in setInterval(), then setInterval executes error

Here is my code

componentDidMount() {
    let that = this;
    setInterval(() => {
        that.setState({number: 1});
    }, 2000);
}

I have writen 'let that = this;', but it's also error. In 2 seconds it executes more than once.

Upvotes: 2

Views: 4990

Answers (1)

RRikesh
RRikesh

Reputation: 14411

Why aren't you using this itself in the setInterval? You have used the fat arrow function, so you still can use this inside.

Here's a sample code:

constructor (props) {
    super(props)
    this.state = {
        number: 0
    } 
  }

componentDidMount(){
  setInterval(() => {
      this.setState({number: parseInt(this.state.number, 10) + 1 });
  }, 2000);

}

render() {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center',}}>
      <Text>
       {this.state.number }
      </Text>
    </View>
  );
}

Expo Demo

Upvotes: 4

Related Questions