How to dispatch a Redux action with a timeout?

后端 未结 12 1985
花落未央
花落未央 2020-11-22 04:14

I have an action that updates the notification state of my application. Usually, this notification will be an error or info of some sort. I need to then dispatch another act

12条回答
  •  傲寒
    傲寒 (楼主)
    2020-11-22 04:54

    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

提交回复
热议问题