Skip to content

Commit

Permalink
Handle promise rejectsion in handleSubmit (jaredpalmer#2136)
Browse files Browse the repository at this point in the history
In 2.0.7, submitForm was changed to propagate any promise rejections when submitting. This is desired behavior when calling submitForm directly, but it can't be caught when using handleSubmit, resulting in unhandled promise rejection errors. Catch the error and log a warning to the console instead.
  • Loading branch information
bespokebob authored and jaredpalmer committed Dec 18, 2019
1 parent 631461a commit 7fd2892
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
7 changes: 6 additions & 1 deletion packages/formik/src/Formik.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -812,7 +812,12 @@ export function useFormik<Values extends FormikValues = FormikValues>({
}
}

submitForm();
submitForm().catch(reason => {
console.warn(
`Warning: An unhandled error was caught from submitForm()`,
reason
);
});
}
);
const handleReset = useEventCallback(e => {
Expand Down
23 changes: 23 additions & 0 deletions packages/formik/test/Formik.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -426,6 +426,29 @@ describe('<Formik>', () => {
}).not.toThrow();
});

it('should not error if onSubmit throws an error', () => {
const FormNoPreventDefault = (
<Formik
initialValues={{ name: 'jared' }}
onSubmit={() => Promise.reject('oops')}
>
{({ handleSubmit }) => (
<button
data-testid="submit-button"
onClick={() =>
handleSubmit(undefined as any /* undefined event */)
}
/>
)}
</Formik>
);
const { getByTestId } = render(FormNoPreventDefault);

expect(() => {
fireEvent.click(getByTestId('submit-button'));
}).not.toThrow();
});

it('should touch all fields', () => {
const { getProps, getByTestId } = renderFormik();
expect(getProps().touched).toEqual({});
Expand Down

0 comments on commit 7fd2892

Please sign in to comment.