Created
September 5, 2018 14:28
-
-
Save jimbolla/d4ab0b7af4ebae96d064b45b7f38e980 to your computer and use it in GitHub Desktop.
react-final-form auto submit on blur
This file contains 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 diff from "object-diff"; | |
import React from "react"; | |
import { FormSpy } from "react-final-form"; | |
class AutoSubmitOnBlur extends React.Component { | |
state = { | |
active: null, | |
values: {} | |
}; | |
onFormSpyChange = async ({ active, values }) => { | |
const isBlurEvent = this.state.active && this.state.active !== active; | |
if (isBlurEvent) { | |
if (this.onBlurPromise) { | |
await this.onBlurPromise; | |
} | |
const difference = diff(this.state.values, values); | |
const hasChanges = Object.keys(difference).length; | |
this.setState({ active, values }); | |
if (hasChanges) { | |
this.onBlurPromise = this.props.onBlur(); | |
await this.onBlurPromise; | |
delete this.onBlurPromise; | |
} | |
} else { | |
this.setState({ active }); | |
} | |
}; | |
render() { | |
return ( | |
<FormSpy | |
subscription={{ active: true, values: true }} | |
onChange={this.onFormSpyChange} | |
/> | |
); | |
} | |
} | |
export default AutoSubmitOnBlur; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment