Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating state within setTimeout (React & React-Native)

What I've been trying to achieve are to update state and to update the same state again, based on Javascript's timer.

The reason why I can't achieve this seems to be the nature of state in React.js.

Here is a snippet of my experimentation...

render() {
    if (this.props.hasError) {
        setTimeout(function(){this.setState({showWarning: true}); }.bind(this), 3000);
    }
    return (
      <View>
        <Blah warning={this.state.showWarning} />
      </View>
    );
}

So, the objective is to change state for only just a few seconds if there is a specific props provided.

This approach seems to hit the limit of updating states, if this.props.hasError gets updated too frequently.

Apologies if this question is too basic. Any suggestion will be appreciated.

like image 819
Hiroki Avatar asked May 24 '26 21:05

Hiroki


1 Answers

You shouldn't update your state in render() function. If you do so, you will end up in an infinite loop, that's why you got that error. You need to use:

componentWillReceiveProps(nextProps){
    if (this.nextProps.hasError) {
        setTimeout(function(){this.setState({showWarning: true}); }.bind(this), 3000);
    }
}

This should resolve your issue.

like image 86
Tim Avatar answered May 26 '26 11:05

Tim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!