Skip to content

Instantly share code, notes, and snippets.

@lelandrichardson
Created September 12, 2017 23:00
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lelandrichardson/ff2392199b62c26759f2bf235676758b to your computer and use it in GitHub Desktop.
Save lelandrichardson/ff2392199b62c26759f2bf235676758b to your computer and use it in GitHub Desktop.
safer react-redux
/* eslint no-restricted-syntax:0 */
const hasOwnProperty = Object.prototype.hasOwnProperty;
function shallowDifferences(a, b) {
const result = [];
if (a === b) {
return result;
}
for (const key in a) {
if (hasOwnProperty.call(a, key) && a[key] !== b[key]) {
result.push(key);
}
}
for (const key in b) {
if (hasOwnProperty.call(b, key) && !hasOwnProperty.call(a, key)) {
result.push(key);
}
}
return result;
}
function compareAndLogIfDifferent(a, b) {
const keys = shallowDifferences(a, b);
if (keys.length > 0) {
console.group('%cFunction expected to be pure was not!', 'color: red;');
console.log('{key}, {first result}, {second result}');
keys.forEach(key => console.log(key, a[key], b[key]));
console.groupEnd();
}
}
function ensureShallowPurity(fn) {
return function wrappedFunction() {
// eslint-disable-next-line prefer-rest-params
const result = fn.apply(this, arguments);
// eslint-disable-next-line prefer-rest-params
const testResult = fn.apply(this, arguments);
compareAndLogIfDifferent(result, testResult);
return result;
};
}
module.exports = ensureShallowPurity;
import { connect } from 'react-redux';
import ensureShallowPurity from './ensureShallowPurity';
function purityWarningReduxConnect(
mapStateToProps,
mapDispatchToProps,
mergeProps,
options,
) {
return connect(
mapStateToProps ? ensureShallowPurity(mapStateToProps) : null,
mapDispatchToProps,
mergeProps,
options,
);
}
module.exports = purityWarningReduxConnect;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment