1
Hello, I’m making a component that shows the current date, but I would like to update it as soon as there is the change, but I was only able to leave it active for change with a timeout, which I think is not a good solution, because it keeps updating all the time unnecessarily or I would have to adjust a high value that could cause a delay in the update time.
this.state = {
curDate : null
}
componentDidMount() {
setInterval( () => {
this.setState({
curDate : new Date().getSeconds()
})
},1000)
}
render() {
return (
<div>
<p>{this.state.curDate}</p>
</div>
);
}
The Reactjs website on Quickstart has an example that evolves to something like what you want, in case it makes a clock with date and everything, that evolves from the most wrong version, until the more correct
– Lucas
What is your question? Your code seems to be OK. The use of
setInterval
in thecomponentDidMount()
is correct if it is to show a clock.– nbkhope
If you just want to show today’s date, just format the value of
new Date().toISOString()
render() itself. You don’t have to keep counting the time. I don’t think anyone’s going to enter your page and wait 24 hours just to see the date change. Probably the person will access the other day, in a new page Load, which again will show the date of the day and not the previous.– nbkhope
I understand that the user can give a Reload, but if it is on the page at the time of the date change the same would not be updated, so I need it to update. The point was that I tested it with seconds and obviously it kept making it yield every second, but switching to getDate() it doesn’t make it yield every second, even with the value of setInterval. My concern was that he was consuming resources only for this, but that’s not the case, I’ve even changed a little following guidelines from a colleague of FB.
– André Agenor