Skip to content

Instantly share code, notes, and snippets.

@klarstrup
Created October 19, 2017 13:20
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 klarstrup/df70702b768cabe47b3af727e78b9c8d to your computer and use it in GitHub Desktop.
Save klarstrup/df70702b768cabe47b3af727e78b9c8d to your computer and use it in GitHub Desktop.
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