Home > Back-end >  How to count how many times a variable is true in an hour/in a day?
How to count how many times a variable is true in an hour/in a day?

Time:05-13

I am coding a motion detection app with React Native and I would like to count how many times the alarm has been triggered in an hour and in a day.

I get the state of the alarm (true/false) with redux toolkit with

    const alarmValue = useSelector((state) => state.alarm.active);

and want to output the number of times the alarm has been triggered in a text field but I can't figure out how to, especially in an hour or in a day. Any ideas are greatly appreciated!

CodePudding user response:

    useEffect(() => {
       // This code will run when the alarm value changes and here you can check if it is changed to true

If (alarmValue) {
// Here you can just Crete a new state variable to store the count and increment it 
}
    })

CodePudding user response:

Hopefully it helps, but in React.js you could try having an array which keeps a record of the state of alarmValue, and then have another variable which keeps a record of how many times in the last 24 hours has the alarm been triggered:

const [alarmValue, setAlarmValue] = useState(false);    
const [timesTriggered, setTimesTriggered] = useState(0);
let alarmArray = [];

Then you will need to use the useEffect hook:

useEffect(() => {
    const appendEveryMinute = setInterval(() => {
        alarmArray.append(alarmValue);
        console.log("This will be called every 60 seconds");
    }, 60000); 
    // alternatively you should be able to do 60 * 1000
    
    const checkTimesTriggered = setInterval(() => {
        for (const alarm of alarmArray) { // for each alarm in the array
            if (alarm) { // if alarm is true
                setTimesTriggered(alarmTriggered   1); // increment timesTriggered
           }
        }

        console.log("Alarm has been triggered "   timesTriggered   " times");

        setTimesTriggered(0) 
        // we reset timesTriggered so it will recalculate every hour

        console.log("This will be called every hour");
    }, 3600000); // alternatively you should be able to do 3600 * 1000

    return () => {
        clearInterval(appendEveryMinute);
        clearInterval(checkTimesTriggered);
    };
});

Maybe this will give you a good start.

  • Related