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
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
Share Improve this question edited Jul 22, 2015 at 10:55 eguneys asked Jul 21, 2015 at 17:39 eguneyseguneys 6,3967 gold badges34 silver badges81 bronze badges 2- As this does work, I probably wouldn't keep recreating a function that always looks the same but instead define it once. – Sebastian Nette Commented Jul 21, 2015 at 17:46
- have you tried setInterval? don't really understand what's async about your increment. Do remember that js event handling is not very precise – softwarenewbie7331 Commented Jul 22, 2015 at 8:01
1 Answer
Reset to default 18The 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.