-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #84 from perimetre/7.5.0
7.5.0
- Loading branch information
Showing
4 changed files
with
34 additions
and
1 deletion.
There are no files selected for viewing
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
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
import { useFormikContext } from 'formik'; | ||
import { debounce } from 'lodash'; | ||
import { useEffect, useMemo, useState } from 'react'; | ||
import fastDeepEqual from 'fast-deep-equal'; | ||
|
||
/** | ||
* Helper component that should be placed under the formik. That submits the form when the values change | ||
*/ | ||
export const FormikSubmitOnChange: React.FC = () => { | ||
const { values, initialValues, submitForm, dirty, errors } = useFormikContext(); | ||
const [previousValues, setPreviousValues] = useState<unknown>(); | ||
|
||
// Wrap it with a debounced method | ||
const submit = useMemo(() => debounce(submitForm, 250, { maxWait: 500 }), [submitForm]); | ||
|
||
useEffect(() => { | ||
const hasErrors = errors && Object.entries(errors).length > 0; | ||
const didChange = values !== initialValues && !fastDeepEqual(previousValues, values); | ||
if (!hasErrors && (dirty || didChange)) { | ||
submit(); | ||
setPreviousValues(values); | ||
} | ||
}, [submit, values, initialValues, dirty, errors, previousValues]); | ||
|
||
return null; | ||
}; |
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