anderlaini
anderlaini

Reputation: 1821

react-native - can't access setState inside component function

I'm learning react-native and now I'm stucked on state lesson with this error:

_this2.setState is not a function.

Here's the current block of code.

...
export default class StopWatch extends Component {

  constructor(props){
    super(props);
    this.state = {
      timeElapsed: null
    }
  }

  handleStartStopClick(){
    var startTime = new Date();

    setInterval(() => {
      this.setState(previousState => {
        return {timeElapsed:new Date() - startTime};
      });
    }, 100);
  }
...

What am I doing wrong?

Upvotes: 6

Views: 2812

Answers (2)

Voi Mập
Voi Mập

Reputation: 809

Try this :

 this.setState({timeElapsed : (new Date() - startTime)})

You must defined your function in constructor with bind(this) or

handleStartStopClick = () => {...}

Upvotes: 3

Moti Azu
Moti Azu

Reputation: 5442

handleStartStopClick is called from a context where this is not your class's instance. You can avoid that by adding .bind(this) to the function you are passing as your click handler.

<TouchableHighlight onPress={this.handleStartStopClick.bind(this)}>

Upvotes: 9

Related Questions