Skip to content

Instantly share code, notes, and snippets.

@mturley
Last active June 21, 2018 23:13
Show Gist options
  • Save mturley/f52c77b004cf832d7fb605d3f1fd2354 to your computer and use it in GitHub Desktop.
Save mturley/f52c77b004cf832d7fb605d3f1fd2354 to your computer and use it in GitHub Desktop.
Another example of reducer handler functions, arrow function shorthand for immediate return, and helper functions
import {
BLUEPRINTS_FILTER_UPDATE_VALUES,
COMPONENTS_FILTER_UPDATE_VALUES, COMPONENTS_FILTER_ADD_VALUE
} from '../actions/filter';
// const filter = (state = [], action) => {
// switch (action.type) {
// case COMPONENTS_FILTER_ADD_VALUE:
// // ...
// return Object.assign({}, state,
// { components: Object.assign({}, state.components,
// { filterValue: updated })
// });
// case SOME_OTHER_ACTION:
// // ...
// return something;
// default:
// return state;
// }
// };
const arrowFn = () => { };
const arrowFn = () => { return thing; };
const arrowFn = () => thing;
// An example of a helper that abstracts common behavior from multple action handlers
const stateWithNewComponent = (state, filterValue, component) => ({
...state,
components: {
...state.components,
[filterValue]: component
}
});
// Object containing:
// keys: action type (as a computed property: [key])
// values: action handlers (reducer-like functions)
// http://www.benmvp.com/learning-es6-enhanced-object-literals/#computed-property-keys
const handlers = {
// One helper handles the whole state for this action
[COMPONENTS_FILTER_ADD_VALUE]: (state, action) => stateWithNewComponent(state, action.filterValue, action.component),
// The above is the same as this, but with the arrow function return shorthand.
[COMPONENTS_FILTER_ADD_VALUE]: (state, action) => {
return stateWithNewComponent(state, action.filterValue, action.component);
},
[COMPONENTS_FILTER_ADD_VALUE]: (state, action) => {
// Advanced example of having different state properties handled by different helpers
return {
filterStuff: someFilterHelper(state.filters, action.newFilter),
errors: errorHelper(state.errors, action.newFilter)
}
},
[COMPONENTS_FAVORITES_ADD_VALUE]: (state, action) => {
// ...
return Object.assign({}, state,
{ components: Object.assign({}, state.components,
{ [key]: updated })
});
}
};
const filter = (state = [], action) => {
const handler = handlers[action.type];
if (handler) {
return handler(state, action);
}
return state;
};
export default filter;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment