Forked from GuillaumeJasmin/createBatchActions.js
Created
September 29, 2018 23:07
-
-
Save marsbomber/dbe740dc54afd67a650817b1b0e11776 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