Skip to content

Instantly share code, notes, and snippets.

@GuillaumeJasmin
Last active March 17, 2019 20:09
Show Gist options
  • Save GuillaumeJasmin/3956fb03becdba50dc18ab9a721b9793 to your computer and use it in GitHub Desktop.
Save GuillaumeJasmin/3956fb03becdba50dc18ab9a721b9793 to your computer and use it in GitHub Desktop.
Batch actions async for redux-batched-actions
import { isPlainObject } from 'lodash';
import { batchActions as batchActionsDefault } from 'redux-batched-actions';
const handleInnerAction = (action, getState) => {
if (typeof action === 'function') {
return new Promise(resolve => {
const innerDispatch = innerAction => resolve(handleInnerAction(innerAction, getState));
action(innerDispatch, getState);
});
} else if (isPlainObject(action)) {
return Promise.resolve(action);
}
throw new Error('dispatch error');
};
const batchActions = actions => (dispatch, getState) => {
const promises = actions.map((action) => handleInnerAction(action, getState));
return Promise.all(promises).then(objectActions => dispatch(batchActionsDefault(objectActions)));
};
// example of use
// classic async dispatch
const fetchItem = (itemId) => (dispatch) => {
fetch(`http://myserver/items/${itemId}`).then(data => {
dispatch({ type: 'ADD_ITEM', item: data });
});
}
// batch dispatch which use a list of classic async actions
const getAllData = (itemsId) => (dispatch) => {
const actions = itemsIds.map(itemId => fetchItem(itemId));
dispatch(batchActions(actions));
}
@Zik42
Copy link

Zik42 commented Mar 17, 2019

dont work, works only if only 1 dispatch in async actions

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment