I am trying to set the state of a self updating Date-obj in my App.js file. The state is then passed down into the DateTime component and works initially fine. But when the state of date updates itself with a setInterval() timer, it doesn't change the state (or time) inside of the component I "drilled" the prop date down to. Shouldn't the DateTime component update itself every second as well? How can I achieve this?
Thanks a lot!
App.js
import React, { useEffect, useState } from 'react';
import DateTime from './components/DateTime';
const App = () => {
const [date, setDate] = useState(new Date());
const hours = date.getHours();
function refreshClock() {
setDate(new Date());
}
useEffect(() => {
const timerId = setInterval(refreshClock, 1000);
return function cleanup() {
clearInterval(timerId);
};
}, []);
return (
<div className="flex items-center justify-center h-screen w-screen">
<DateTime date={date} />
</div>
)
}
export default App
DateTime.js
import React, { useEffect } from 'react'
const DateTime = ({date}) => {
const day = date.getDate();
const month = date.getMonth() + 1;
const year = date.getFullYear();
const hours = date.getHours();
const minutes = date.getMinutes() < 10 ? `0${date.getMinutes()}` : date.getMinutes();
const currentTime = `${hours}:${minutes}`;
const weekdays = ['Sonntag','Montag','Dienstag','Mittwoch','Donnerstag','Freitag','Samstag' ];
const weekday = weekdays[date.getDay()];
const currentDate = `${day}.${month}.${year}`;
return (
<div className="z-10">
<p className="dark:text-black text-white text-center text-10xl leading-11">{currentTime}</p>
<p className="dark:text-black text-white text-center text-4xl">{weekday}, der {currentDate}</p>
</div>
)
}
export default DateTime