Issue
I’m starting React and I saw I could set up a clock using a fat-arrow function inside my setInterval():
class Clock extends React.Component {
constructor(props) {
super(props)
this.state = { date: new Date() }
this.timer = null
}
componentDidMount() {
this.timer = window.setInterval(() => {
this.setState({ date: new Date() })
}, 1000)
}
But I did not manage to get the same result with a regular function (below). I think it’s linked to the "this" keyword creating a new context inside a regular function? I have no idea how to fix this:
componentDidMount() {
this.timer = window.setInterval(function() {
this.setState({ date: new Date() })
}, 1000)
}
Thank you for your time
Solution
This isn’t exactly because a new this
is created for a regular function (btw, don’t confuse the context and this
), rules for regular functions and this
are:
- a new object in the case of a constructor
- undefined in functions call in strict mode
- the current object if the function is called as a method
Your case is the third, but the trick is that when using setInterval
or setTimeout
, the callback function is called as a method, but in the global scope (this
==window
).
The classical way is to save this
in a variable. Because the function can access the context it was created in, it will remember this variable:
var self = this;
this.timer = window.setInterval(function() {
self.setState({ date: new Date() })
}, 1000)
You can also use bind
Answered By – Kaddath
Answer Checked By – Senaida (BugsFixing Volunteer)