Skip to content

Commit

Permalink
Merge pull request #84 from perimetre/7.5.0
Browse files Browse the repository at this point in the history
7.5.0
  • Loading branch information
AssisrMatheus authored Aug 19, 2022
2 parents 6a75dba + 249e5c6 commit 65fc2bf
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 1 deletion.
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Fixed

## [7.5.0] 2022-08-19

### Added

- Added `FormikSubmitOnChange` component

## [7.4.0] 2022-08-17

### Added
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@perimetre/ui",
"description": "A component library made by @perimetre",
"version": "7.4.0",
"version": "7.5.0",
"repository": {
"type": "git",
"url": "git+https://github.com/perimetre/ui.git"
Expand Down
26 changes: 26 additions & 0 deletions src/components/FormikSubmitOnChange/index.tsx
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;
};
1 change: 1 addition & 0 deletions src/components/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,4 @@ export * from './ExpertCard';
export * from './ProgramCard';
export * from './BaseCard';
export * from './HorizontalResizeablePanel';
export * from './FormikSubmitOnChange';

0 comments on commit 65fc2bf

Please sign in to comment.