Process action creators too

This commit is contained in:
Alfred Melch 2020-02-01 18:57:58 +01:00
parent 16cdc1acf7
commit 444ef30587

View File

@ -34,6 +34,7 @@ export const createStore = options => {
/** Turn a reducer definition object to a function
* @param {Object} reducer: Object definition of a reducer: {<type>: (state, payload) => <newState>}
* @param {Object} options
* @returns {Function}: Proper reducer
*/
function makeReducerFn(reducer, { onUpdate, logging }) {
@ -49,17 +50,30 @@ function makeReducerFn(reducer, { onUpdate, logging }) {
}
}
/** Returns a set of actions that are bound to the store
* @param {Object} actions: {<name>: payload => ({dispatch, type}) => }
/** Produces a set of actions that are bound to a specific store
* The thunks object can contain action creators and/or thunks.
* - Action creators: args => action
* are dispatched directly when called
* - Thunks args => dispatch => dispatch(action)
* are called with dispatch as first argument.
* The dispatch function will be patched to insert an action type if not given.
* This action type will be the SNAKE_CASE'd action name
* @param {Object} thunks
* @param {Function} dispatch
* @returns {object}
*/
function bindThunks(thunks, dispatch) {
const _thunks = {}
const boundThunks = {}
for (let name of Object.keys(thunks)) {
const defaultType = camelToSnakeCase(name).toUpperCase()
_thunks[name] = (...args) =>
thunks[name](...args)(patchDispatch(dispatch, defaultType))
const patchedDispatch = patchDispatch(dispatch, defaultType)
boundThunks[name] = (...args) => {
const thunk = thunks[name](...args)
if (typeof thunk !== 'function') patchedDispatch(thunk)
else thunk(patchedDispatch)
}
}
return _thunks
return boundThunks
}
const camelToSnakeCase = str =>