Skip to content

Instantly share code, notes, and snippets.

@TCotton
Created February 13, 2017 12:31
Show Gist options
  • Save TCotton/753631a2ee441d724726ab8473fb743f to your computer and use it in GitHub Desktop.
Save TCotton/753631a2ee441d724726ab8473fb743f to your computer and use it in GitHub Desktop.
Dynamically create a react redux reducer
export function createReducer(initialState, reducerMap) {
return (state = initialState, action) => {
const reducer = reducerMap[action.type];
return reducer
? reducer(state, action.payload)
: state;
};
}
// used in the example below
import {createReducer} from '../../utils';
// Add the following for IE compatability
Object.assign = Object.assign || require('object-assign');
const initialState = {
'count': 0,
'receiving': false,
'pages': 0,
'documents': []
};
export default createReducer(initialState, {
['RECEIVED_DOCUMENTS']: (state, payload) => {
return {
'count': payload.count,
'pages': payload.pages,
'documents': payload.documents,
'receiving': false
};
},
['RETRIVING_DOCUMENTS']: (state, payload) => {
return Object.assign({}, state, {
'receiving': true
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment