const createAction = (type) => {
const actionCreator = (payload) => ({
type,
payload,
})
actionCreator.type = type
return actionCreator
}
const createReducer = (actionHandlers, initialState) => (
(state = initialState, action) => {
const handler = actionHandlers[action.type]
return handler ? handler(state, action) : state
}
)
usage:
// Action creator acts both as actionCreator and actionType
export const fetchMany = createAction('FETCH_MANY')
console.log(fetchMany.type) // 'FETCH_MANY'
console.log(fetchMany()) // {type: 'FETCH_MANY', payload: undefined}
// dispatch(fetchMany(payload))
const actionHandlers = {
[fetchMany.type]: (state, action) => ({ ...state, ...action.payload })
}
const initialState = {}
const fooReducer = createReducer(actionHandlers, initialState)