Forked from haradakunihiko/memoizedConnectReduxForm.js
Created
October 16, 2015 15:22
-
-
Save kevinold/8d63afe8630e728c5f08 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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