Quantcast
Channel: How to dispatch a Redux action with a timeout? - Stack Overflow
Viewing all articles
Browse latest Browse all 15

Answer by Yash for How to dispatch a Redux action with a timeout?

$
0
0

If you want timeout handling on selective actions, you can try the middleware approach. I faced a similar problem for handling promise based actions selectively and this solution was more flexible.

Lets say you your action creator looks like this:

//action creator
buildAction = (actionData) => ({
    ...actionData,
    timeout: 500
})

timeout can hold multiple values in the above action

  • number in ms - for a specific timeout duration
  • true - for a constant timeout duration. (handled in the middleware)
  • undefined - for immediate dispatch

Your middleware implementation would look like this:

//timeoutMiddleware.js
const timeoutMiddleware = store => next => action => {

  //If your action doesn't have any timeout attribute, fallback to the default handler
  if(!action.timeout) {
    return next (action)
  }

  const defaultTimeoutDuration = 1000;
  const timeoutDuration = Number.isInteger(action.timeout) ? action.timeout || defaultTimeoutDuration;

//timeout here is called based on the duration defined in the action.
  setTimeout(() => {
    next (action)
  }, timeoutDuration)
}

You can now route all your actions through this middleware layer using redux.

createStore(reducer, applyMiddleware(timeoutMiddleware))

You can find some similar examples here


Viewing all articles
Browse latest Browse all 15

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>