diff --git a/lib/potent-reducer.js b/lib/potent-reducer.js index a8a4078..453bc63 100644 --- a/lib/potent-reducer.js +++ b/lib/potent-reducer.js @@ -34,6 +34,7 @@ export const createStore = options => { /** Turn a reducer definition object to a function * @param {Object} reducer: Object definition of a reducer: {: (state, payload) => } + * @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: {: 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 =>