Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fire periodic actions using setTimeout and dispatcher in redux

Tags:

How/Where can I dispatch actions periodically? Using recursive setTimeout to make a countdown.

Taken from the example, something similar to this:

// Can also be async if you return a function
export function incrementAsync() {
  return dispatch => {
    (function _r() {
      setTimeout(() => {
        // Yay! Can invoke sync or async actions with `dispatch`
        dispatch(increment());
        _r();
      }, 1000);
    })();
  };
}

So is this a good idea, or there is a better approach to this problem, like using middlewares or creating actions from somewhere else?

I prefer a generic version of this, where I can control start/stop of the timer via the store.

I've setup a sample implementation please take a look at https://gist.github.com/eguneys/7023a114558b92fdd25e

like image 260
eguneys Avatar asked Jul 21 '15 17:07

eguneys


People also ask

How do I dispatch actions in setTimeout?

js import store from './store' // ... let nextNotificationId = 0 export function showNotificationWithTimeout(text) { const id = nextNotificationId++ store. dispatch(showNotification(id, text)) setTimeout(() => { store. dispatch(hideNotification(id)) }, 5000) } // component.

What is an action in Redux can I dispatch an action in reducer?

Dispatching an action within a reducer is an anti-pattern. Your reducer should be without side effects, simply digesting the action payload and returning a new state object. Adding listeners and dispatching actions within the reducer can lead to chained actions and other side effects.

Which functions are used to trigger an action in Redux?

Redux includes a utility function called bindActionCreators for binding one or more action creators to the store's dispatch() function. Calling an action creator does nothing but return an object, so you have to either bind it to the store beforehand, or dispatch the result of calling your action creator.


1 Answers

The approach you suggest is fine, although a bit convoluted. In general, I'd set intervals inside component lifecycle methods (e.g. componentDidMount / componentWillUnmount) and avoid actions setting intervals on other actions.

If you absolutely need this flexibility, a better bet is to use Rx for async management, and dispatch the actions at the very end of observable chain. This way you use Redux where it shines (synchronous updates) and leave asynchronous composition to Rx.

like image 199
Dan Abramov Avatar answered Sep 27 '22 22:09

Dan Abramov