Created
October 30, 2017 18:10
-
-
Save leongaban/12e652b9d720ff6e7a7c069698aa708b to your computer and use it in GitHub Desktop.
cleanMapStateToProps function for redux
This file contains hidden or 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
/* 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; | |
}, {}) | |
}); |
Author
leongaban
commented
Oct 30, 2017
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment