Skip to content

Instantly share code, notes, and snippets.

@jimbolla
Created September 5, 2018 14:28
Show Gist options
  • Save jimbolla/d4ab0b7af4ebae96d064b45b7f38e980 to your computer and use it in GitHub Desktop.
Save jimbolla/d4ab0b7af4ebae96d064b45b7f38e980 to your computer and use it in GitHub Desktop.
react-final-form auto submit on blur
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