I need to setInterval when main component. i tried setting it in constructor like
constructor(props) {
super(props);
this.props.fetchUserInfo();
this.props.fetchProducts();
setInterval(console.log('1'), 1000);
}
or inside componentDidMount
componentDidMount = () => {
setInterval(console.log('1'), 1000);
};
but it always logs '1' once. How to launch interval properly?
setInterval(console.log('1'), 1000); calls console.log('1') and passes its return value into setInterval, exactly the way foo(bar()) calls bar and passes its return value to foo.
You want to pass a function reference to it:
setInterval(function() {
console.log('1');
}, 1000);
Or if you need this to be the same inside that function and are not yet using ES2015 syntax:
setInterval(function() {
console.log('1');
}.bind(this), 1000);
Function#bind returns a new function that, when called, calls the original using the this value you give it.
Or if you are using ES2015 syntax
setInterval(() => {
console.log('1');
}, 1000);
That will close over the this where it's created, no need for bind.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With