0

How could we use a setState inside setTimeout. I declared a property inside constructor function. I used this.setState({ count: index }); inside setTimeout it throws an error like Uncaught TypeError: this.setState is not a function

constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
    this.onMouseDown = this.onMouseDown.bind(this);
  }
onMouseDown() {
    this.timer();
  }
timer() {
    for (var i = 1; i <= 90; i++) {
      (function(index) {
        setTimeout(function() {
          this.setState({ count: index });
        }, index * 10);
      })(i);
    }
  }

I tried a lot don't know how to fix this. And why it is wrong?.Please get me out of this problem..

1

1 Answer 1

0

this is not refering the compnent this.setState is defined on component this

 timer() {
    const objThis  = this; //store this.
        for (var i = 1; i <= 90; i++) {
          (function(index) {
            setTimeout(function() {
              objThis.setState({ count: index });
            }, index * 10);
          })(i);
        }
      }
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.