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;