0

I'm not sure what I'm missing here. I'm new to React and JS in general. Below is the full code for the one file along with the piece I'm interested in fixing.

I'm attempting to use setInterval to update the state every second so that the time re-renders and updates accordingly on screen. The console logs out the 'Hello!' statement every second but the time never updates. What am I missing here?

Thanks for any help!

import React, { Component } from 'react';

import DateDay from '../Date/Date';
import Time from '../Time/Time';
import './timedate.css'



class TimeDate extends Component{
  state = {
    curDate: '',
    curTime: '',
  };


componentDidMount() {


  const optionsDate = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
  const optionsTime = { hour: '2-digit', minute: '2-digit' };
  const today = new Date();

  setInterval( () => {
    this.setState({curDate : today.toLocaleString("en-us", optionsDate)}),
    this.setState({curTime : today.toLocaleString("en-us", optionsTime).slice(0, -3)}) //slice removes the AM/PM
    console.log('Hello!')
  },1000)
}

render () {
  let { curDate } = this.state;
  let { curTime } = this.state;

  return (
    <div className="timedate">
       <DateDay 
          dateDay={curDate}
        />
        <Time 
          time={curTime}
        />
    </div>
         );
      }
}

export default TimeDate;

3 Answers 3

2

You are always using the same date

componentDidMount() {


  const optionsDate = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
  const optionsTime = { hour: '2-digit', minute: '2-digit' };
  // const today = new Date(); captures current date for every next call.

  setInterval( () => {
    const today = new Date(); // move it here
    this.setState({curDate : today.toLocaleString("en-us", optionsDate)}),
    this.setState({curTime : today.toLocaleString("en-us", optionsTime).slice(0, -3)}) //slice removes the AM/PM
    console.log('Hello!')
  },1000)
}

Also you do want to stop interval when component got unmounted. You could do it this way

componentDidMount() {
  ...
  this.intervalId = setInterval(...)
}

componentWillUnmount() {
  clearInterval(this.intervalId)
}
Sign up to request clarification or add additional context in comments.

Comments

0

You have initialized the state in the wrong way. State initialization should be in the constructor.

constructor() {
  super();
  this.state = {
    curDate: '',
    curTime: '',
  }
}

1 Comment

Not with property initializers.
0

You are not rendering the seconds, field so every second the data won't update also you need to calculate date inside setInterval

class TimeDate extends React.Component {
      state = {
        curDate: "",
        curTime: ""
      };

      componentDidMount() {
        const optionsDate = {
          weekday: "long",
          year: "numeric",
          month: "long",
          day: "numeric"
        };
        const optionsTime = {
          hour: "2-digit",
          minute: "2-digit",
          second: "2-digit"
        };

        setInterval(() => {
          const today = new Date();
          this.setState({ curDate: today.toLocaleString("en-us", optionsDate) }),
            this.setState({ curTime: today.toLocaleString("en-us", optionsTime) }); //slice removes the AM/PM
          console.log("Hello!");
        }, 1000);
      }

    render () {
      let { curDate } = this.state;
      let { curTime } = this.state;

      return (
        <div className="timedate">
           <DateDay 
              dateDay={curDate}
            />
            <Time 
              time={curTime}
            />
        </div>
      );
    }
}

Working DEMO

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.