Created
January 5, 2019 23:20
-
-
Save aigoncharov/b40939d8fcc55488b45dbaa8ab0e806d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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