skip to Main Content

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


  1. Maintain all the state variables in type string.
    clockTime and alarmTime are set to type number with value 0 initially. And then clockTime is set to a string value in updateClockTime. alarmTimeis set to the return type of onChange event handler of input. Type mismatch while comparing two variables will return false in most cases.

    clockTime === alarmTime checks for equality in both value and type. If you want only the values to be checked, you should use clockTime == alarmTime, although in your case, I’d suggest to maintain a consistent datatype

    Login or Signup to reply.
  2. The 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:

    const { useState, useEffect } = React;
    
    const AlarmClock = () => {
      const [clockTime, setClockTime] = useState("00:00:00");
      const [alarmTime, setAlarmTime] = useState("0");
      const [status, setStatus] = useState(false);
    
      useEffect(() => {
        if (status && clockTime === alarmTime) {
          console.log("get up", clockTime, alarmTime);
          setStatus(false);
        }
      }, [clockTime, alarmTime, status]);
    
      const updateClockTime = () => {
        let currentTime = new Date();
        let hours = currentTime.getHours();
        let minutes = currentTime.getMinutes();
        let seconds = currentTime.getSeconds();
    
        if (hours.toString().length === 1) hours = "0" + hours;
        if (minutes.toString().length === 1) minutes = "0" + minutes;
        if (seconds.toString().length === 1) seconds = "0" + seconds;
    
        let clockFormat = `${hours}:${minutes}:${seconds}`;
        //console.log("Clock: ", clockFormat);
        setClockTime(clockFormat);
      };
    
      const handleAlarmTimeChange = (e) => {
        console.log("alarm time: ", e.target.value);
        setAlarmTime(e.target.value);
      };
    
      const handleToggle = () => {
        setStatus(!status);
      };
    
      const handleReset = () => {
        setAlarmTime("0");
        setStatus(false);
      };
    
      useEffect(() => {
        setInterval(updateClockTime, 1000);
      }, []);
    
      return (
        <div>
          <div className="wrapper">
            <h1>Alarm Clock</h1>
    
            <div className="containt">
              <h2>{clockTime}</h2>
              <input
                type="time"
                step="1"
                value={alarmTime}
                onChange={handleAlarmTimeChange}
              />
            </div>
            <button onClick={handleToggle}>
              {status ? "Stop Alarm" : "Start Alarm"}
            </button>
            <button onClick={handleReset}>Reset Alarm</button>
          </div>
        </div>
        );
    };
    
    const rootElement = document.getElementById("root");
    const root = ReactDOM.createRoot(rootElement);
    
    root.render(<AlarmClock/>);
    <script src="https://unpkg.com/react@18/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
    <div id='root'></div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search