Last active
February 5, 2018 02:48
-
-
Save slightlytyler/c0623daf8c6e2f8a8a626fd488016e91 to your computer and use it in GitHub Desktop.
A HOC to handle "autosaving" when a formik form changes value
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
// @flow | |
import { isEqual, noop } from 'lodash/fp'; | |
import React, { Component, createFactory } from 'react'; | |
import { setDisplayName, wrapDisplayName } from 'recompose'; | |
import debounce from 'common/utilities/debounce'; | |
const withSubmitOnChange = (BaseComponent: Class<*>) => { | |
const factory = createFactory(BaseComponent); | |
type Props = { | |
handleChange: Function, | |
handleSubmit: Function, | |
}; | |
class WithSubmitOnChange extends Component { | |
static contextTypes = { | |
formik: React.PropTypes.shape({ | |
handleChange: React.PropTypes.func, | |
handleSubmit: React.PropTypes.func, | |
}), | |
}; | |
static childContextTypes = { | |
formik: React.PropTypes.shape({ | |
handleChange: React.PropTypes.func, | |
}), | |
}; | |
constructor(props: Props) { | |
super(props); | |
this.commit = debounce(300, props.handleSubmit).bind(this, { | |
preventDefault: noop, | |
}); | |
} | |
getChildContext() { | |
return { | |
formik: { | |
...this.context.formik, | |
handleChange: this.handleChange, | |
}, | |
}; | |
} | |
componentWillReceiveProps(nextProps: Props) { | |
if (!isEqual(this.props.handleSubmit, nextProps.handleSubmit)) { | |
this.commit = debounce(300, nextProps.handleSubmit).bind(this, { | |
preventDefault: noop, | |
}); | |
} | |
} | |
handleChange = (e: any) => { | |
this.props.handleChange(e); | |
this.commit(); | |
}; | |
commit: Function; | |
props: Props; | |
render() { | |
return factory(this.props); | |
} | |
} | |
if (process.env.NODE_ENV !== 'production') { | |
return setDisplayName(wrapDisplayName(BaseComponent, 'withSubmitOnChange'))( | |
WithSubmitOnChange | |
); | |
} | |
return WithSubmitOnChange; | |
}; | |
export default withSubmitOnChange; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment