Skip to content

Instantly share code, notes, and snippets.

@marsbomber
Forked from GuillaumeJasmin/createBatchActions.js
Created September 29, 2018 23:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marsbomber/dbe740dc54afd67a650817b1b0e11776 to your computer and use it in GitHub Desktop.
Save marsbomber/dbe740dc54afd67a650817b1b0e11776 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));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment