Last active
March 17, 2019 20:09
-
-
Save GuillaumeJasmin/3956fb03becdba50dc18ab9a721b9793 to your computer and use it in GitHub Desktop.
Batch actions async for redux-batched-actions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
dont work, works only if only 1 dispatch in async actions