Skip to content

Commit

Permalink
Add useResetSubmitErrors hook
Browse files Browse the repository at this point in the history
  • Loading branch information
alanpoulain committed Feb 26, 2021
1 parent ec4cc75 commit 170421f
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 2 deletions.
36 changes: 34 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,14 @@
It's very intuitive to clear an error if the field containing the error is changing, and `final-form-submit-errors` does exactly that.

## Install
`npm i final-form-submit-errors`
or
`npm i final-form-submit-errors`
or
`yarn add final-form-submit-errors`

## Usage

With the `SubmitErrorsSpy` component:

```jsx
import { Form } from 'react-final-form';
import { submitErrorsMutators, SubmitErrorsSpy } from 'final-form-submit-errors';
Expand All @@ -42,6 +44,36 @@ const MyForm = () => (
);
```

With the `useResetSubmitErrors` hook:

```jsx
import { Form } from 'react-final-form';
import { submitErrorsMutators, useResetSubmitErrors } from 'final-form-submit-errors';

const FormContent = ({ handleSubmit }) => {
useResetSubmitErrors();

return (
<form onSubmit={handleSubmit}>
{/* ... */}
</form>
);
};

const MyForm = () => (
<Form
onSubmit={onSubmit}
mutators={{
// add submitErrorsMutators to your mutators
...submitErrorsMutators,
}}
render={(props) => (
<FormContent {...props} />
)}
/>
);
```

## License

MIT. Copyright (c) Anton Ignatev.
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export { default as submitErrorsMutators } from './submitErrorsMutators'
export { default as SubmitErrorsSpy } from './SubmitErrorsSpy'
export { default as useResetSubmitErrors } from './useResetSubmitErrors'
24 changes: 24 additions & 0 deletions src/useResetSubmitErrors.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { useRef } from 'react';

import { useForm, useFormState } from 'react-final-form';

const useResetSubmitErrors = () => {
const { mutators } = useForm();
const { values } = useFormState({
subscription: { values: true },
});
const prevValues = useRef(values);
useFormState({
onChange: ({ values }) => {
mutators.resetSubmitErrors({
current: values,
prev: prevValues.current,
});

prevValues.current = values;
},
subscription: { values: true },
});
};

export default useResetSubmitErrors;

0 comments on commit 170421f

Please sign in to comment.