While redux itself is entirely synchronous, you can use a middleware such as redux-thunk
to handle asynchronous actions.
A "thunk" is another name for a callback. It is a function that is usually passed as an argument to be called at a later time.
To use, apply the middleware to your redux store:
import ReduxThunk from 'redux-thunk';
const store = createStore(
reducer,
applyMiddleware(ReduxThunk)
);
This allows you to pass a thunk to dispatch
instead of a plain object. The middleware will recognize the thunk and call it. The thunk takes the store's dispatch
method as a parameter:
// an asynchronous action - "thunk"
// This will wait 1 second, and then dispatch the 'INCREMENT' action
const delayedIncrement = dispatch => setTimeout(() => {
dispatch({
type: 'INCREMENT'
});
}, 1000);
// dispatch the thunk.
// note: no () as we're passing the function itself
store.dispatch(delayedIncrement);