const createAction = (type) => {
const actionCreator = (payload) => ({
type,
payload,
})
actionCreator.type = type
return actionCreator
}
const createReducer = (actionHandlers, initialState) => (
(state = initialState, { type, payload }) => {
const handler = actionHandlers[type]
return handler ? handler(state, payload) : 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, payload) => ({ ...state, ...payload })
}
const initialState = {}
const fooReducer = createReducer(actionHandlers, initialState)