Understanding setInterval in React component [duplicate]

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



Understanding setInterval in React component [duplicate]



This question already has an answer here:



I am learning React and in general Javascript so my apologies if it is very obvious.



I have a React Clock Component that is suppose to update the timer.


componentDidMount()
this.timer = setInterval(this.tick, 1000);


componentWillUnmount()
clearInterval(this.timer);


tick()
this.setState(
date: new Date()
);



This throws the error that setState is not a function.


setState



However if i change the code of setInterval like this


componentDidMount()
this.timer = setInterval(() => this.tick(), 1000);



It works fine.



I am confused, as per my understanding setInterval needs a function and timer. Why if i provide the function name this.tick it doesn't work. Why I have to wrap it in another anonymous function. I am from PHP background and in PHP we can pass other function names where it needs a callback parameter.


setInterval


this.tick



Thanks



This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.





Because this gets lost in a callback. Except you use arrow functions as they get their context lexically.
– Jonas Wilms
Aug 10 at 14:14


this




Popular posts from this blog

make 2 or more post in bootsrap

Store custom data using WC_Cart add_to_cart() method in Woocommerce 3

Firebase Auth - with Email and Password - Check user already registered