Show Buttons
Share On Facebook
Share On Twitter
Share On Google Plus
Share On Linkdin
Share On Reddit
Share On Stumbleupon
Contact us
Hide Buttons

Create Reducer for Redux Applications

In redux you will have to gen­er­ate reduc­ers to update the state. You will have to call rel­e­vant reducer based on the action type.

For exam­ple,


function setSurveySuccess(state, action) { ... return newState; } function setSurveyFail(state, action) { ... return newState; } function currentSurveyReducer(state, action) { switch(action.type) { case 'CREATE_SURVEY': return setSurveySuccess(state, action); case 'CREATE_SURVEY_FAIL': return setSurveyFail(state, action); default: return state; } }

In a large appli­ca­tion, you end up repeat­ing the above switch case state­ments all over the place. There is a use­ful util­ity func­tion createReducer in redux-create-reducer which helps us avoid writ­ing such a repet­i­tive code.

import { createReducer } from 'redux-create-reducer';

function currentSurveyReducer = createReducer(state, {
    'CREATE_SURVEY': setSurveySuccess,
    'CREATE_SURVEY_FAIL': setSurveyFail
});

The imple­men­ta­tion this sim­ple util­ity func­tion is shown below.


You may also like...