Add createReducer - a typesafe reducer factory using object map (including getType() support) #106
MasGaNo posted onGitHub
First thank you for this project, it's very cool and help us to reduce dramatically the number of files, lines of code, increase the readability and enforce the definition 👍
Is your feature request related to a problem?
<!-- A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] -->
In some of our projects we have very big reducers with big switch
statement.
So that's why I want to have this kind of approach from Redux documentations:
export const todos = createReducer([], {
[ActionTypes.ADD_TODO]: (state, action) => {
const text = action.text.trim()
return [...state, text]
}
})
//
function createReducer(initialState, handlers) {
return function reducer(state = initialState, action) {
if (handlers.hasOwnProperty(action.type)) {
return handlers[action.type](state, action)
} else {
return state
}
}
}
This approach helps us to reduce the cyclomatic complexity of the file, and allow us to test easily each reducer.
Describe a solution you'd like
<!-- A clear and concise description of what you want to happen. -->
In the same way I want to enforce the definition based on typesafe-actions
, I want to have a way to create the reducers based on the list of actions
created with the different createAction
method and to get the correct state
and action
on each reducer
.
Who does this impact? Who is this for?
<!-- Who is this for? All users? TypeScript users? Beginners? Advanced? Yourself? People using X, Y, X, etc.? -->
Well... for everybody I guess.
Describe alternatives you've considered
<!-- A clear and concise description of any alternative solutions or features you've considered. -->
I made a try, but it wasn't fully a success... So if you can help me to complete this approach and/or to improve it, it will be great. To illustrate my purpose, I prepared a demo-project here. I have 2 main concerns:
create-reducers.ts: I get a transpilation error. It's not necessary related totypesafe-actions
, so I will continue to investigate.- reducers.ts: My goal is to remove the
constant
approach. So it work like a charm withconstant
even if I created the actions withcreateStandardAction
, but if I try to deal withgetType
, the magic disappear.
Additional context
<!-- Add any other context or links about the feature request here. -->
I know that I definitely need to improve my skills about Advanced Definition, so probably, type
definition defined in the create-reducers.ts
file can easily be improved to manage the different use-case.
Don't hesitate to tell me if you find this discussion appropriate or not here.
Thanks.
Fund this Issue
Rewarded pull request
Click to copy link
Recent activities