Update status by observing the date change

Asked

Viewed 542 times

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>
      );
}
  • 1

    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

  • 1

    What is your question? Your code seems to be OK. The use of setInterval in the componentDidMount() is correct if it is to show a clock.

  • 1

    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.

  • 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.

1 answer

0

I don’t think you have much of a choice when it comes to using an interval. What you can do to decrease the number of executions (even you don’t have as many features as this being used, so you don’t have to worry) is in the load of your application count how much time is left before the day turns. Then you put a timeout with the right timing, and in theory, you only have to run it once a day. When the date turns you put another timeout to 24 and so on.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.