Skip to content

Instantly share code, notes, and snippets.

@aigoncharov
Created January 5, 2019 23:20
Show Gist options
  • Save aigoncharov/b40939d8fcc55488b45dbaa8ab0e806d to your computer and use it in GitHub Desktop.
Save aigoncharov/b40939d8fcc55488b45dbaa8ab0e806d 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 = state[action.type]
if (!reducer) {
return state
}
// Run the reducer if present
return reducer(state, action)
}
const reducerLoadingMap = (actionInit, actionSuccess, actionError) => ({
[actionInit.type]: () => true,
[actionSuccess.type]: () => false,
[actionError.type]: () => false,
})
class CatsGetInit extends ActionStandard {}
class CatsGetSuccess extends ActionStandard {}
class CatsGetError extends ActionStandard {}
const reducerCatsLoading = createReducer(
false,
reducerLoadingMap(CatsGetInit, CatsGetSuccess, CatsGetError),
)
/* Now we can easily extend it like this:
const reducerCatsLoading = createReducer(
false,
{
...reducerLoadingMap(CatsGetInit, CatsGetSuccess, CatsGetError),
... some custom stuff
}
)
*/
const reducerCatsData = createReducer(undefined, {
[CatsGetSuccess.type]: () => action.payload,
})
const reducerCatsError = createReducer(undefined, {
[CatsGetError.type]: () => action.payload,
})
const reducerCats = combineReducers({
data: reducerCatsData,
loading: reducerCatsLoading),
error: reducerCatsError,
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment