CustardBun
CustardBun

Reputation: 3877

Reducers in redux starting to look redundant - any way to combine them in a nicer way?

Using redux, I have a bunch of actions and a bunch of reducers that coincide with each of the action types.

Each of the actions map to a different part of the state being updated (all the action creators are primarily for fetching data from an API, for example, which maps to some part of the state). Our reducers currently look rather silly (simplified to A, B, C, for the sake of example):

export const rootReducer = combineReducers({
    somePartOfStateA: someAReducer,
    somePartOfStateB: someBReducer,
    somePartOfStateC: someCReducer,
    ... (and many other reducers)
});

function someAReducer(state = [], action) {
    switch (action.type) {
        case FETCH_SOME_A:
            return action.payload;
        default:
            return state;
    }
}

function someBReducer(state = [], action) {
    switch (action.type) {
        case FETCH_SOME_B:
            return action.payload;
        default:
            return state;
    }
}

function someCReducer(state = [], action) {
    switch (action.type) {
        case FETCH_SOME_C:
            return action.payload;
        default:
            return state;
    }
}
// and a bunch of pretty much identical reducers continue below

From my understanding, the purpose of having them split is so that each reducer handles a part of the state's namespaces. The resulting reducers are simple, but pretty much the same thing over and over. Is there a recommended way to consolidate all of these reducers per piece of state?

Upvotes: 0

Views: 139

Answers (1)

Yury Tarabanko
Yury Tarabanko

Reputation: 45106

Reducer is just a function. You could use higher order function to make reducer for you.

const makeSingleActionReducer = type => (state, action) => 
  action.type === type ? action.payload : state

export const rootReducer = combineReducers({
  somePartOfStateA: makeSingleActionReducer(FETCH_SOME_B)
  ...
})

Also you could go further by creating a config {stateKey: actionType, ...} and loop over it.

Upvotes: 3

Related Questions