Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

187
Visualizações
How to count how many times a value is true in an hour/day in React?

I'm coding an alarm app and want to count how many times the alarm has been triggered in an hour and in a day. I use redux toolkit to handle the state of the alarm (true/false) and the reducer countAlarm to increment the count. Right now handleCount dispatches countAlarm every time alarmValue is true. I would like to count how many times the alarmValue is true in an hour and in a day. How do I do that?

      const dispatch = useDispatch();
      const countValue = useSelector((state) => state.count.value);
      const alarmValue = useSelector((state) => state.alarm.active);

      const handleCount = () => {
        if (alarmValue) {
        dispatch(countAlarm());
      }}

      useEffect(() => {
        handleCount()
      }, [alarmValue])

      return (
        <View>
          <Text>{countValue}</Text>
        </View>

        ...

countAlarm:

    import { createSlice } from '@reduxjs/toolkit';

    const initialStateValue = {
        value: 0
    }

    const countSlice = createSlice({
        name: 'count',
        initialState: initialStateValue,
        reducers: {
            countAlarm: (state = initialStateValue) => {
                state.value++;
            },
        }
    });

    export const {countAlarm} = countSlice.actions;
    export default countSlice.reducer;

alarmValue:

    import { createSlice } from '@reduxjs/toolkit';

    const initialStateValue = {
        active: false,
    }

    const alarmSlice = createSlice({
        name: 'alarm',
        initialState: initialStateValue,
        reducers: {
            alarmOn: (state = initialStateValue) => {
                state.active = true;
            },
            alarmOff: (state = initialStateValue) => {
                state.active = false;
            },
        }
    });

    export const {alarmOn, alarmOff} = alarmSlice.actions;
    export default alarmSlice.reducer;
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

What do you mean by in an hour / in a day? I would append the data:

const initialStateValue = {
        value: 0,
        numberOfAlarmsInDay: 0
        numberOfAlarmsPerHour: {
           perFirstHour: 0,
           perSecondHour: 0,
           ...
        }
    }

Then, you need

  • either the time as a a PayloadAction or you read something like the system data in the reducer to determine which counter to set
  • a trigger for a new day to reset the values, most likely as another action. If you want to do that in a reducer (with the first alarm of a new day), you need to keep the day to know when to reset again -> but the data may be dirty!

Hope this helpsyou a bit to advance further!

about 4 years ago · Juan Pablo Isaza Relatório

0

You should not really go this "roundabout through the component". Instead, let your countSlice just react to the alamSlice's alarmOn action:

    import { createSlice } from '@reduxjs/toolkit';
    import { alarmOn } from './alarmSlice'

    const initialStateValue = {
        value: 0
    }

    const countSlice = createSlice({
        name: 'count',
        initialState: initialStateValue,
        reducers: {
          // reducers for "this slice"
        },
        extraReducers: builder => {
          // reducers for actions owned by other slices
          builder.addCase(alarmOn, (state) => { state.value++; })
        }
    });

See allow many reducers to respond to the same action in the Redux Style guide.

(Of course you could also just keep the counter in your alarmSlice; depending on the complexity that could also be a fine solution)

PS: don't do (state = initialStateValue) => { - you don't need to initialize your state like this, createSlice takes care of that.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda