Created
October 19, 2017 13:20
-
-
Save klarstrup/df70702b768cabe47b3af727e78b9c8d to your computer and use it in GitHub Desktop.
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 keyChange = (oldProps, newProps, propsHandlersMap = {}) => | |
R.forEachObjIndexed((handler, keysString) => { | |
const keys = keysString.split(','); | |
if (!R.equals(R.pick(keys)(oldProps), R.pick(keys)(newProps))) { | |
handler(newProps); | |
} | |
})(propsHandlersMap); | |
// This little baby will(combined with those R utility functions) help | |
// reduce your componentWillReceiveProps methods like so: | |
// This | |
componentWillReceiveProps = newProps => { | |
if (!R.equals(newProps.query, this.props.query)) { | |
newProps.fetchCatalogs(); | |
} | |
if (!R.equals(newProps.catalogs, this.props.catalogs)) { | |
newProps.fetchStores(R.pluck('store_id', newProps.catalogs)); | |
} | |
}; | |
// Becomes | |
componentWillReceiveProps = newProps => | |
keyChange(this.props, newProps, { | |
query: ({ fetchCatalogs }) => fetchCatalogs(), | |
catalogs: ({ catalogs, fetchStores }) => fetchStores(R.pluck('store_id', catalogs)), | |
}); | |
// And | |
// This | |
componentWillReceiveProps(newProps) { | |
if(!R.equals(this.props.latitude, newProps.latitude) || !R.equals(this.props.longitude, newProps.longitude) { | |
this.map.panTo({ lat: newProps.latitude, lng: newProps.longitude }) | |
} | |
} | |
// Becomes | |
componentWillReceiveProps(newProps) { | |
keyChange(this.props, newProps, { | |
[['latitude', 'longitude']]: ({ latitude, longitude }) => | |
this.map.panTo({ lat: latitude, lng: longitude }), | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment