I have a react application used to take attendance. The attendance records the time of signin.
The problem I am facing with the app is that the time doesn’t get updated with real time. After the first render of the app, the time remains constant. (The time gets updated when the app gets reloaded though)
The code I am supplying is just a sample of the whole problem, but it expresses the problem fully.
App.js
import React from 'react';
import { BrowserRouter, Route, Routes } from 'react-router-dom';
import Signin from './pages/Signin';
export const date = new Date();
export const options = { hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: true };
const currentTime = new Intl.DateTimeFormat('en-US', options).format(date);
export const currTime = currentTime.slice(0, 8);
export default function App() {
return (
<div className='App'>
<BrowserRouter>
<Routes>
<Route path="/" element={<Signin />} />
</Routes>
</BrowserRouter>
</div>
);
}
Signin.js
import React from 'react';
import { currTime } from '../App';
function Signin() {
React.useEffect(() => {
const interval = setInterval(() => {
console.log(currTime);
}, 1000);
return () => {
clearInterval(interval);
}
}, []);
return (<>Sign In</>);
}
export default Signin;
The same value is logged each time the interval runs
For example, if I ran this at 05:38:25
, I will keep getting 05:38:25
even by another time like 05:48:25
.
How do I fix this, such that I will get 05:48:25
by 05:48:25
even if the app was rendered by 05:38:25
3
Answers
import React, { useState, useEffect } from ‘react’;
function Signin() {
const [currentTime, setCurrentTime] = useState(new Date());
}
export default Signin;
The issue you’re facing is related to the fact that the currTime value is computed only once during the initial rendering of the App component and doesn’t get updated afterward. To achieve real-time updates, you need to use the useState hook to manage the current time in the Signin component and update it at regular intervals.