Here I have created an alarm application, so here when I have set the button, it does not convert to stop alarm, and when the time of the clock and alarm time are the same, I want a console like "get up" until I refresh the page, and clockTime === alarmTime always gives the same results, so why does this happen and how do I recover that? Could anyone suggest, please? The code is given below.
import React, { useState } from "react";
const AlarmClock = () => {
const [clockTime, setClockTime] = useState(0);
const [alarmTime, setAlarmTime] = useState(0);
const [status, setStatus] = useState(false);
const updateClockTime = () => {
let currentTime = new Date();
let hours = currentTime.getHours();
let minutes = currentTime.getMinutes();
let seconds = currentTime.getSeconds();
let clockFormat = `${hours}:${minutes}:${seconds}`;
setClockTime(clockFormat);
if (clockTime === alarmTime) {
console.log("get up",clockTime ,alarmTime);
setStatus(false);
}
};
const handleAlarmTimeChange = (e) => {
setAlarmTime(e.target.value);
};
const handleToggle = () => {
setStatus(!status);
};
const handleReset = () => {
setAlarmTime(0);
setStatus(false);
};
setInterval(updateClockTime, 1000);
setInterval(alarm, 1000);
return (
<div>
<div className="wrapper">
<h1>Alarm Clock</h1>
<div className="containt">
<h2>{clockTime}</h2>
<input
type="time"
value={alarmTime}
onChange={handleAlarmTimeChange}
/>
</div>
<button onClick={handleToggle}>
{status ? "Stop Alarm" : "Start Alarm"}
</button>
<button onClick={handleReset}>Reset Alarm</button>
</div>
</div>
);
};
export default AlarmClock;
2
Answers
Maintain all the state variables in type
string
.clockTime
andalarmTime
are set to typenumber
with value0
initially. And thenclockTime
is set to a string value inupdateClockTime
.alarmTime
is set to the return type ofonChange
event handler ofinput
. Type mismatch while comparing two variables will returnfalse
in most cases.clockTime === alarmTime
checks for equality in both value and type. If you want only the values to be checked, you should useclockTime == alarmTime
, although in your case, I’d suggest to maintain a consistent datatypeThe comparison is getting failed for
clockTime === alarmTime
. You are storing both states as strings, so you have to check the correct format before comparison. Here’s the modified code snippet that works: