Skip to content

Instantly share code, notes, and snippets.

@leongaban
Created October 30, 2017 18:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leongaban/12e652b9d720ff6e7a7c069698aa708b to your computer and use it in GitHub Desktop.
Save leongaban/12e652b9d720ff6e7a7c069698aa708b to your computer and use it in GitHub Desktop.
cleanMapStateToProps function for redux
/* eslint-disable import/prefer-default-export */
import { initialStates } from '../reducers';
const defaultPropDef = {
value: null,
writable: false,
configurable: true,
enumerable: true
};
// Grabs all appropriate states to use in a container
const getters = Object
.keys(initialStates)
.reduce((gets, reducer) => (
Object.keys(initialStates[reducer])
.reduce((_, propName) => (
Object.defineProperty(gets, propName, {
...defaultPropDef,
value: state => state[reducer][propName]
})
), gets)
), {});
/* eslint-disable key-spacing, no-multi-spaces */
export const cleanMapStateToProps = (incl = []) => (state, props) => ({
...props,
...incl.reduce((obj, key) => {
if (getters[key]) return { ...obj, [key]: getters[key](state, props) };
/* eslint-disable no-console */
console.warn(`WARNING: "${key}" is not specified in any reducer's initialState`);
/* eslint-enable */
return obj;
}, {})
});
@leongaban
Copy link
Author

leongaban commented Oct 30, 2017

const mapDispatchToProps = dispatch => ({
  signOut: () => { dispatch(signOut()); },
  onAuthStateChange: () => { dispatch(onAuthStateChange()); },
  toggleNotification: (notification, notificationMessage, type) => {
    dispatch(toggleNotification(notification, notificationMessage, type));
  }
});

export default connect(cleanMapStateToProps([
  'user',
  'notification',
  'notificationMessage',
  'notificationType'
]), mapDispatchToProps)(MainContainer);

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