How to dispatch a Redux action with a timeout?

后端 未结 12 1971
花落未央
花落未央 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 05:02

    The appropriate way to do this is using Redux Thunk which is a popular middleware for Redux, as per Redux Thunk documentation:

    "Redux Thunk middleware allows you to write action creators that return a function instead of an action. The thunk can be used to delay the dispatch of an action, or to dispatch only if a certain condition is met. The inner function receives the store methods dispatch and getState as parameters".

    So basically it returns a function, and you can delay your dispatch or put it in a condition state.

    So something like this is going to do the job for you:

    import ReduxThunk from 'redux-thunk';
    
    const INCREMENT_COUNTER = 'INCREMENT_COUNTER';
    
    function increment() {
      return {
        type: INCREMENT_COUNTER
      };
    }
    
    function incrementAsync() {
      return dispatch => {
        setTimeout(() => {
          // Yay! Can invoke sync or async actions with `dispatch`
          dispatch(increment());
        }, 5000);
      };
    }
    

提交回复
热议问题