Reputation: 2799
I want to use objects to decide what part of my reducer is run. My current example is mainly from the redux docs. Example:
export const todos = createReducer(initialState, {
[ADD_TODO]: function (state, action) {
return [ ...state, text: action.text ]
}
})
function createReducer(initialState, handlers) {
return function reducer(state = initialState, action) {
if (handlers.hasOwnProperty(action.type)) {
return handlers[action.type](state, action)
}
return state;
}
}
This works fine for most use-cases but I would prefer to have the same function run for multiple actions. For example in a typical reducer I would do the following:
case: ADD_TODO:
case: ADD_TODOS:
// Do stuff and return state
return [ ...state, text: action.text ]
I want to be able to do something like:
createReducer(initialState, {
[ADD_TODO, ADD_TODOS]: function (state, action) {
// do stuff
Any ideas for a clean approach?
Upvotes: 0
Views: 982
Reputation: 67459
You just need to define the function separately, and reuse it for multiple keys:
function addTodo(state, action) {
// do stuff
}
export default createReducer(initialState, {
[ADD_TODO] : addTodo,
[ADD_TODOS] : addTodo,
});
Upvotes: 1