Skip to content

Instantly share code, notes, and snippets.

@danseethaler
Last active July 7, 2017 04:31
Show Gist options
  • Save danseethaler/d1e154788956ee05bdd139a3e1bc812f to your computer and use it in GitHub Desktop.
Save danseethaler/d1e154788956ee05bdd139a3e1bc812f to your computer and use it in GitHub Desktop.
Simplify Redux Reducer
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;
}
}
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
});
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')
});
@danseethaler
Copy link
Author

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. The orig_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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment