2

I am new to the react-redux application. My actions consist of a little hierarchy like this one:

{
    type:'FITLER',
    filterType: 'FILTER_COUNTRY',
    payload: countries
}

In my reducer, among other functions, I am writing one of my reducer as:

function FilterValue(state, action){
    switch(action.type){
        CASE FILTER:break;
        CASE FILTER_CLEAR_ALL:break;
        default:
    }
}

I was wondering if I should make nested switch statements for my typical case like:

function FilterValue(state, action){
    switch(action.type){
        CASE FILTER:
             switch(action.filterType){
                  CASE FILTER_COUNTRY:break;
                  CASE FILTER_REGION: break;
                  default:
             }
        CASE FILTER_CLEAR_ALL:
        default:
    }
}

I looked into these articles and SO questions but none of them answered about this programming practice.

Object Literals vs Switch Case

Switch-Case - Object literals

Reduce Reducers vs Combine Reducers

EDIT: I am already using reduceReducers and Thunk middleware. My question is only regarding nested switchcase.

technazi
  • 888
  • 4
  • 21
  • 42

1 Answers1

0

Nesting reducers:

Nesting reducers is a bad practice. You will want to keep your reducers (and state slices) as flat as possible. Hence, splitting will yield a better developing experience in terms of updating slices of your state. Check combineReducers().

About the switch case:

Consider refactoring your reducer's from switch formation

export function todos(state = [], action) {
  switch (action.type) {
    case ActionTypes.ADD_TODO:
      const text = action.text.trim()
      return [...state, text]
    default:
      return state
  }
}

To hashtable formation

export const todos = createReducer([], {
  [ActionTypes.ADD_TODO]: (state, action) => {
    const text = action.text.trim()
    return [...state, text]
  }
})

You can write the following helper to accomplish this:

function createReducer(initialState, handlers) {
  return function reducer(state = initialState, action) {
    if (handlers.hasOwnProperty(action.type)) {
      return handlers[action.type](state, action)
    } else {
      return state
    }
  }
}

Key benefits of using this approach:

  1. Simple, whether use or not depends on you.
  2. don't worry about the variable name duplicated
  3. can use destruct action and state
  4. can use ES6 arrow function syntax
  5. hashTable is faster than switch when having a lot of cases
  6. don't need annoying break and default

References:

https://redux.js.org/recipes/reducing-boilerplate#generating-reducers https://github.com/reduxjs/redux/issues/883

Tomer
  • 1,521
  • 1
  • 15
  • 26