I am trying to build a timer with a button, click to start, and stop the timer. I have been trying different ways and reading StackOverflow past questions, but still can not make it work on my application. I have already set up the applyMiddleware(thunk) to the store.
Basically I have a button like
<button onClick={props.timerHandler}>
{props.isRunning ? "TIMER STOP" : "TIMER START"}
</button>
Theprops.timerHandler is to change the isRunning value to true and false.
In reducer funtion, I have tried something like this, but it is not working
case "TIMER":
let timer = null;
clearInterval(timer);
if (state.isRunning === true)
timer = setInterval(() => {
return state + 1;
}, 1000);
return {
...state,
isRunning: !state.isRunning,
};
In action, I have then tried the code like this, and export to use in my App.js, but also not working.
export const timer = () => (dispatch, getState) => {
let timer = null;
clearInterval(timer);
if (getState().isRunning === true)
timer = setInterval(() => {
dispatch(incAction());
}, 1000);
};
Please help, and let me know if any clarification needed. Thanks