简体   繁体   中英

clear interval from redux middleware

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM