6

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?

2 Answers 2

9

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)}>
Sign up to request clarification or add additional context in comments.

3 Comments

it worked! I was missing the bind(this) block! thank you!
Adding to this, I would recommend you to bind your function in your constructor instead of in onPress. Otherwise, you will bind your function each time the component is re-render and it can result in performance decrease.
@AntoineGrandchamp Definitely, this is the performant way to do it
3

Try this :

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

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

handleStartStopClick = () => {...}

4 Comments

How would using deprecated version of setState help?
I think ,Problem is setState is not function, also it sets one State to another State. Like this: this.setState( state : value you want set )
Yes. the problem is that handleStartStopClick is being called without binding thus having wrong context. So your answer not only doesn't help but promotes deprecated API.
Okay thank @YuryTarabanko . I have fixed my answer ^^. We can use bind(this) or use direct arrow function in ES 6

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.