My application displays a greeting such as "Good Morning" depending on the time of day. I have a function that checks the time and changes the greeting based on what time it is. I can't use componentDidMount
since it's a functional component, so I'm using React.useEffect
. The issue is this does not run on startup, there is a small delay where the app displays "Good Morning" and then will change to "Good Afternoon". How can I remove this delay.
Function that determines greeting based on time
const [currGreeting, setCurrGreeting] = useState(greetings[0]);
//Involves saving to localStorage so the transition can be seamless if the app is exited and returned to
function updateGreeting(){
time = new Date();
let hour = time.getHours();
console.log(hour);
if(12 > hour && hour > 5){
setCurrGreeting(greetings[0]);
console.log("Good Morning")
const curSessionGreeting = JSON.parse(localStorage.getItem("sessionGreeting")) || [];
if(curSessionGreeting != currGreeting){
localStorage.setItem("sessionGreeting", JSON.stringify(greetings[0]));
setCurrGreeting(greetings[0]);
}
}
if((18 > hour && hour > 12) || hour === 12){
setCurrGreeting(greetings[1]);
console.log("Good Afternoon")
const curSessionGreeting = JSON.parse(localStorage.getItem("sessionGreeting")) || [];
if(curSessionGreeting != currGreeting){
localStorage.setItem("sessionGreeting", JSON.stringify(greetings[1]));
setCurrGreeting(greetings[1]);
}
}
if(hour > 18 || (5 > hour && hour > 0)){
setCurrGreeting(greetings[2]);
console.log("Good Evening")
const curSessionGreeting = JSON.parse(localStorage.getItem("sessionGreeting")) || [];
if(curSessionGreeting != currGreeting){
localStorage.setItem("sessionGreeting", JSON.stringify(greetings[2]));
setCurrGreeting(greetings[2]);
}
}
}
Updates the greeting
React.useEffect(() => {
setInterval(()=>updateGreeting(), 1000);
});
Where the app is rendering
return (
<div>
<div style = {{display: 'flex', fontFamily: 'Work Sans', fontSize: 25,marginBottom: 25, color: '#CDCACA'}}>
<text>{currGreeting}</text>
</div>
</div>
);
};
export default App;
You should run one updateGreeting
before executing setInterval
since this delay the first updateGreeting
execution one second 1000ms
it does that asynchronously :
React.useEffect(() => {
updateGreeting()//first execution
setInterval(()=>updateGreeting(), 1000);
},[]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With