How to dispatch a Redux action with a timeout?

2018-12-31 08:28发布

I have an action that updates notification state of my application. Usually, this notification will be an error or info of some sort. I need to then dispatch another action after 5 seconds that will return the notification state to initial one, so no notification. The main reason behind this is to provide functionality where notifications disappear automatically after 5 seconds.

I had no luck with using setTimeout and returning another action and can't find how this is done online. So any advice is welcome.

13条回答
柔情千种
2楼-- · 2018-12-31 08:41

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

查看更多
只靠听说
3楼-- · 2018-12-31 08:47

I would recommend also taking a look at the SAM pattern.

The SAM pattern advocates for including a "next-action-predicate" where (automatic) actions such as "notifications disappear automatically after 5 seconds" are triggered once the model has been updated (SAM model ~ reducer state + store).

The pattern advocates for sequencing actions and model mutations one at a time, because the "control state" of the model "controls" which actions are enabled and/or automatically executed by the next-action predicate. You simply cannot predict (in general) what state the system will be prior to processing an action and hence whether your next expected action will be allowed/possible.

So for instance the code,

export function showNotificationWithTimeout(dispatch, text) {
  const id = nextNotificationId++
  dispatch(showNotification(id, text))

  setTimeout(() => {
    dispatch(hideNotification(id))
  }, 5000)
}

would not be allowed with SAM, because the fact that a hideNotification action can be dispatched is dependent on the model successfully accepting the value "showNotication: true". There could be other parts of the model that prevents it from accepting it and therefore, there would be no reason to trigger the hideNotification action.

I would highly recommend that implement a proper next-action predicate after the store updates and the new control state of the model can be known. That's the safest way to implement the behavior you are looking for.

You can join us on Gitter if you'd like. There is also a SAM getting started guide available here.

查看更多
人气声优
4楼-- · 2018-12-31 08:47

its simple. use trim-redux package and write like this in componentDidMout or other place and kill it in componentWillUnmount.

componentDidMount(){
   this.tm =  setTimeout(function(){ 
                      setStore({ age: 20 });
              }, 3000);
}

componentWillUnmount(){
   clearTimeout(this.tm);
}
查看更多
伤终究还是伤i
5楼-- · 2018-12-31 08:48

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);
  };
}
查看更多
人间绝色
6楼-- · 2018-12-31 08:48

Whenever you do setTimeout please make sure you also clear the timeout using clearTimeout when your component un mounts in componentWillUnMount life cycle method

store.dispatch({ type: 'SHOW_NOTIFICATION', text: 'You logged in.' })
this.timeout = setTimeout(() => {
  store.dispatch({ type: 'HIDE_NOTIFICATION' })
}, 5000)

componentWillUnMount(){
   clearTimeout(this.timeout);
}
查看更多
弹指情弦暗扣
7楼-- · 2018-12-31 08:50

Redux itself is a pretty verbose library, and for such stuff you would have to use something like Redux-thunk, which will give a dispatch function, so you will be able to dispatch closing of the notification after several seconds.

I have created a library to address issues like verbosity and composability, and your example will look like the following:

import { createTile, createSyncTile } from 'redux-tiles';
import { sleep } from 'delounce';

const notifications = createSyncTile({
  type: ['ui', 'notifications'],
  fn: ({ params }) => params.data,
  // to have only one tile for all notifications
  nesting: ({ type }) => [type],
});

const notificationsManager = createTile({
  type: ['ui', 'notificationManager'],
  fn: ({ params, dispatch, actions }) => {
    dispatch(actions.ui.notifications({ type: params.type, data: params.data }));
    await sleep(params.timeout || 5000);
    dispatch(actions.ui.notifications({ type: params.type, data: null }));
    return { closed: true };
  },
  nesting: ({ type }) => [type],
});

So we compose sync actions for showing notifications inside async action, which can request some info the background, or check later whether the notification was closed manually.

查看更多
登录 后发表回答