2

i have to say, that i searching for answer in hours and nothing helped me, so here my problem:

componentDidMount() {
  var self = this
  console.log(`INIT keys ${this.props.variants}`); // INIT KEYS [Object], [Object] ...
  this.interval = setInterval(function() {
    console.log(`Keys ${self.props.variants}`); // Keys ...
  }.bind(self), 1000)
}

Init keys exists, but keys inside interval not.
Can someone help me? :)

6
  • A lot can happen in 1,000ms. It's not a big surprise that the object has changed one second later, but this small bit of code doesn't give us enough to venture a guess as to why. Commented Jun 1, 2017 at 14:31
  • Is selfdefined ? Shouldn't you use this inside of your function instead of self? Commented Jun 1, 2017 at 14:31
  • @Ksyqo, OP isn't using this inside the callback (but uses self), so an arrow function wouldn't help here. Commented Jun 1, 2017 at 14:33
  • 1
    I believe your problem is in using self inside interval function. Try console.log(Keys ${this.props.variants}); instead Commented Jun 1, 2017 at 14:34
  • @JordanRunning thanks! Its definetly my fault, something is happen with my array of objects. For now i look for a trouble in another place, thanks again! Commented Jun 1, 2017 at 14:37

1 Answer 1

1

In your setInterval bound, you will have to use this and not self. Also, you don't need to redeclare this:

componentDidMount() {
  console.log(`INIT keys ${this.props.variants}`);
  this.interval = setInterval(function() {
    console.log(`Keys ${this.props.variants}`);
  }.bind(this), 1000)
}

If you can use arrow functions, you can ignore the bind as an arrow function doesn't redeclare this:

componentDidMount() {
  console.log(`INIT keys ${this.props.variants}`);
  this.interval = setInterval(() => {
    console.log(`Keys ${this.props.variants}`);
  }, 1000)
}
Sign up to request clarification or add additional context in comments.

1 Comment

thanks a lot, it was really helpful. I had a similar issue

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.