0

My middleware looks like

export const timerMiddleware = store => next => action => {
  if (action.type === "START_TIMER") {
    // console.log("timer");
    action.interval = setInterval(
      () => store.dispatch({ type: "TICK", currentTime: Date.now() }),
      1000
    );
    debugger;
  } else if (action.type === "STOP_TIMER") {
    //console.log(store);
    debugger;
    console.log(action.interval);
    clearInterval(action.interval);
  }
  next(action);
};

on Start timer the clock is ticking, but on stop_timer i loose the reference of setInterval. so unable to stop the clock. what i am missing here. https://codesandbox.io/s/xrmnwr7y8z

John Doe
  • 135
  • 1
  • 12

1 Answers1

3

You probably don't want to mutate the action. Each time you get into the middleware you will have a new action, so your interval will be lost. action.interval also isn't in line with the flux standard action schema. You could have a let outside of your middleware like

let interval;
const timerMiddleware ...

and then go

interval = setInterval // interval will now be a number which is a reference to your interval 

Then when it's time to clear it

clearInterval(interval)

But if you wanted to be more immutable, you do have access to the store in your middleware

const interval = setInterval(...)
store.dispatch({
    type: "SET_YOUR_INTERVAL"
    payload: interval
});

Then in your reducer you can store that under state.someInterval or whatever

case "SET_YOUR_INTERVAL":
    return {
        someInterval: action.payload
    }

and then by the time you get back into the middleware and the action is "STOP_TIMER" you can use store.getState() to get the reference to the current state. Then you can go clearInterval(currentState.someInterval)

and then store.dispatch you can dispatch an action to clean up the interval in state

For more info about the return values of setTimeout and setInterval: setInterval/setTimeout return value

3stacks
  • 1,880
  • 1
  • 16
  • 21
  • I was just following this [guide](https://www.codementor.io/vkarpov/beginner-s-guide-to-redux-middleware-du107uyud). – John Doe Feb 25 '18 at 02:55