Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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