Created
February 13, 2017 12:31
-
-
Save TCotton/753631a2ee441d724726ab8473fb743f to your computer and use it in GitHub Desktop.
Dynamically create a react redux reducer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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