Last active
July 7, 2017 04:31
-
-
Save danseethaler/d1e154788956ee05bdd139a3e1bc812f to your computer and use it in GitHub Desktop.
Simplify 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
const initialState = []; | |
// Using initialState as a default parameter uses the initial state on first render | |
export default function (state = initialState, action) { | |
switch (action.type) { | |
case 'SET_ATTRACTIONS': | |
return action.attractions; | |
default: | |
return state; | |
} | |
} |
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
import { combineReducers } from 'redux'; | |
import reducerEvents from './reducerEvents'; | |
import reducerAttractions from './reducerAttractions'; | |
import reducerGuides from './reducerGuides'; | |
import reducerSponsors from './reducerSponsors'; | |
export default combineReducers({ | |
events: reducerEvents, | |
attractions: reducerAttractions, | |
guides: reducerGuides, | |
sponsors: reducerSponsors | |
}); |
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
import { combineReducers } from 'redux'; | |
function returnStateSlice(expectedAction, valueKey, state = [], action) { | |
if (expectedAction === action.type) return action[valueKey]; | |
return state; | |
} | |
export default combineReducers({ | |
events: returnStateSlice.bind(null, 'SET_EVENTS', 'events'), | |
attractions: returnStateSlice.bind(null, 'SET_ATTRACTIONS', 'attractions'), | |
guides: returnStateSlice.bind(null, 'SET_GUIDES', 'guides'), | |
sponsors: returnStateSlice.bind(null, 'SET_SPONSORS', 'sponsors') | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This gist shows how to reduce reducer files! The
example_reducer.js
simple returns the values provided by the action regardless of the previous state. Theorig_reducer_combining.js
references four files doing the same thing. This allows use to get rid of the additional files an have all logic in a single two-line function.