Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save kevinold/8d63afe8630e728c5f08 to your computer and use it in GitHub Desktop.
Save kevinold/8d63afe8630e728c5f08 to your computer and use it in GitHub Desktop.
import { connect } from 'react-redux';
import { createSelectorCreator } from 'reselect';
import { reduxForm } from 'redux-form';
function memoize(func, equalityCheck = (a, b) => a === b) {
const lastArgsCache = {};
const lastResultCache = {};
return (...args) => {
const memoizeKey = args.pop();
const lastArgs = lastArgsCache[memoizeKey];
const lastResult = lastResultCache[memoizeKey];
if (lastArgs !== undefined &&
args.every((value, index) => equalityCheck(value, lastArgs[index]))) {
return lastResult;
}
const result = func(...args);
lastArgsCache[memoizeKey] = args;
lastResultCache[memoizeKey] = result;
return result;
};
}
function createSelector(...args) {
return createSelectorCreator(memoize)(...args);
}
export function connectReduxForm(...args) {
const formName = args[0].form;
const selector = createSelector(
({ form }, { formKey }) => form && form[formName] && (formKey ? form[formName][formKey] : form[formName]),
( state, { formKey } ) => formKey,
( state, { formKey } ) => formKey || '_default_memoize_key',
( form, formKey ) => formKey ? { form: { [formName]: { [formKey]: form } } } : { form: { [formName]: form } }
);
return DecoratedComponent => connect(selector)(reduxForm(...args)(DecoratedComponent));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment