Skip to content

Instantly share code, notes, and snippets.

@aigoncharov
Last active January 8, 2019 18:37
Show Gist options
  • Save aigoncharov/f4dfd5caeee0960b845567d612e51a3a to your computer and use it in GitHub Desktop.
Save aigoncharov/f4dfd5caeee0960b845567d612e51a3a to your computer and use it in GitHub Desktop.
const createReducer = (initialState, reducerMap) => (
state = initialState,
action,
) => {
// Pick a reducer from the object by key
const reducer = reducerMap[action.type]
if (!reducer) {
return state
}
// Run the reducer if present
return reducer(state, action)
}
const reducerLoading = (actionInit, actionSuccess, actionError) =>
createReducer(false, {
[actionInit.type]: () => true,
[actionSuccess.type]: () => false,
[actionError.type]: () => false,
})
class CatsGetInit extends ActionStandard {}
class CatsGetSuccess extends ActionStandard {}
class CatsGetError extends ActionStandard {}
const reducerCatsData = createReducer(undefined, {
[CatsGetSuccess.type]: () => action.payload,
})
const reducerCatsError = createReducer(undefined, {
[CatsGetError.type]: () => action.payload,
})
const reducerCats = combineReducers({
data: reducerCatsData,
loading: reducerLoading(CatsGetInit, CatsGetSuccess, CatsGetError),
error: reducerCatsError,
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment