Be the first user to complete this post
|
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:
- Passing the store down implicitly via context in a react redux app
- combineReducers in reduxjs explained
- imperative vs declarative/functional programming
- Using React with Backbone Models
- Generating container components with connect utility in react redux app