Be the first user to complete this post

  • 0
Add to List

Create Reducer for Redux Applications

In redux you will have to generate reducers to update the state. You will have to call relevant reducer based on the action type. For example,


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 application, you end up repeating the above switch case statements all over the place. There is a useful utility function createReducer in redux-create-reducer which helps us avoid writing such a repetitive code.
import { createReducer } from 'redux-create-reducer';

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

The implementation this simple utility function is shown below. [wpgist id="dcb86657def2bd9390a170b8a4f17092" file="createReducer.js"]



Also Read:

  1. Redux: Implementing store from scratch
  2. Generating container components with connect utility in react redux app
  3. Reactjs flux architecture - Visualized
  4. imperative vs declarative/functional programming
  5. Passing the store down implicitly via context in a react redux app