Reputation: 453
Currently I'm working on Alarm clock app and I'm using ReactJS. Problem occurs when I try to compare state of current time and state of alarm time.
This is my function which I use for getting current time and insert it in state.
//Insert current time to state
function currentTime(){
let time = new Date().toLocaleTimeString('it-IT');
let hours = time.substr(0,2);
let minutes = time.substr(3,2);
let seconds = time.substring(time.length-2)
setTime(prevState => ({
...prevState,
currentHour:hours,
currentMinute:minutes,
currentSecond:seconds
}))
}
Same as before ,but here I'm getting date
//Insert current date to state
function currentDate(){
let date = new Date();
let day = days[date.getDay()];
setTime(prevState => ({
...prevState,
currentDay:day
}))
}
For refresh after every second ,so clock is actually ticking I used this. Every second currentTime() ,currentDate() and checkTime() is called.
//Update current time every second
useEffect(()=>{
const interval = setInterval(() => {
currentTime();
currentDate();
checkTime();
}, 1000);
return () => clearInterval(interval);
},[])
And here is the problem. Function checkTime is supposed to check every second if alarmHours state is filled or not.
function checkTime(){
if(!time.alarmHours){
console.log('please set alarm');
}else{
console.log('alarm set')
}
}
It keeps throwing 'please set alarm' even if alarmHours state is filled. For filling it I'm using Alarm.js component which is called by clicking 'set alarm' button in top right corner. Input box shows up ,and after filling just click 'Set Alarm'. States will be filled but checkTime function is acting like not and keeps throwing 'please set alarm' in console. Does anybody know what can be the problem? Thank you .
Link for codesandbox is here
Upvotes: 0
Views: 534
Reputation: 11
SetInterval doesn't work as expected with react-hooks. You can go through this guide by Dan Abramov to understand how to use it better.
Upvotes: 0
Reputation: 883
Your setInterval is invoked only when the component mount or dismount because the dependency is an empty array, while in your case you need to make it depend on the time aswell, since the time is the state that is what the alarm is changing
useEffect(()=>{
const interval = setInterval(() => {
currentTime();
currentDate();
checkTime();
}, 1000);
return () => clearInterval(interval);
},[time])
Try this
Upvotes: 2