Skip to content

Commit

Permalink
fix(create-form.js): add return for onSubmit function in handleSubmit
Browse files Browse the repository at this point in the history
This commit fixes and issue where onSubmit runs silently in the background because of a missing
return statement in handleSubmit.

fix #152
  • Loading branch information
dlebech committed Dec 29, 2021
1 parent 66019ba commit 273dbe7
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 2 deletions.
4 changes: 2 additions & 2 deletions lib/create-form.js
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ export const createForm = (config) => {
.then(() => validateFunction(values))
.then((error) => {
if (util.isNullish(error) || util.getValues(error).length === 0) {
clearErrorsAndSubmit(values);
return clearErrorsAndSubmit(values);
} else {
errors.set(error);
isSubmitting.set(false);
Expand Down Expand Up @@ -163,7 +163,7 @@ export const createForm = (config) => {
);
}

clearErrorsAndSubmit(values);
return clearErrorsAndSubmit(values);
});
}

Expand Down
46 changes: 46 additions & 0 deletions test/specs/library.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -650,6 +650,52 @@ describe('createForm', () => {
expect(errors.country).toBe('');
});
});

it('returns a promise that only resolves when onSubmit resolves - without validation', async () => {
// Test case created for reproducing a bug where the onSubmit function
// would not get "waited" for when calling handleSubmit manually due to a
// missing return statement in handleSubmit.
const values = [];

const {handleSubmit} = createForm({
onSubmit: async () => {
await new Promise((resolve) => setTimeout(resolve, 10));
values.push(1);
},
});

const myOtherHandler = async () => {
await handleSubmit();
values.push(2);
};

await myOtherHandler();

// This test case failed before fixing the bug, See top of this test case.
expect(values).toEqual([1, 2]);
});

it('returns a promise that only resolves when onSubmit resolves - with validation', async () => {
// See test case above.
const values = [];

const {handleSubmit} = createForm({
validate: () => true, // Dummy validation just to make sure that code path is taken.
onSubmit: async () => {
await new Promise((resolve) => setTimeout(resolve, 10));
values.push(1);
},
});

const myOtherHandler = async () => {
await handleSubmit();
values.push(2);
};

await myOtherHandler();

expect(values).toEqual([1, 2]);
});
});

describe('validateField', () => {
Expand Down

0 comments on commit 273dbe7

Please sign in to comment.