Skip to content

Commit

Permalink
Merge pull request #153 from dlebech/return-onsubmit-promise
Browse files Browse the repository at this point in the history
  • Loading branch information
larrybotha committed Jan 6, 2022
2 parents 66019ba + 273dbe7 commit 7df1b1d
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 7df1b1d

Please sign in to comment.