Skip to content

Commit 7df1b1d

Browse files
authored
Merge pull request tjinauyeung#153 from dlebech/return-onsubmit-promise
2 parents 66019ba + 273dbe7 commit 7df1b1d

File tree

2 files changed

+48
-2
lines changed

2 files changed

+48
-2
lines changed

lib/create-form.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -130,7 +130,7 @@ export const createForm = (config) => {
130130
.then(() => validateFunction(values))
131131
.then((error) => {
132132
if (util.isNullish(error) || util.getValues(error).length === 0) {
133-
clearErrorsAndSubmit(values);
133+
return clearErrorsAndSubmit(values);
134134
} else {
135135
errors.set(error);
136136
isSubmitting.set(false);
@@ -163,7 +163,7 @@ export const createForm = (config) => {
163163
);
164164
}
165165

166-
clearErrorsAndSubmit(values);
166+
return clearErrorsAndSubmit(values);
167167
});
168168
}
169169

test/specs/library.spec.js

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -650,6 +650,52 @@ describe('createForm', () => {
650650
expect(errors.country).toBe('');
651651
});
652652
});
653+
654+
it('returns a promise that only resolves when onSubmit resolves - without validation', async () => {
655+
// Test case created for reproducing a bug where the onSubmit function
656+
// would not get "waited" for when calling handleSubmit manually due to a
657+
// missing return statement in handleSubmit.
658+
const values = [];
659+
660+
const {handleSubmit} = createForm({
661+
onSubmit: async () => {
662+
await new Promise((resolve) => setTimeout(resolve, 10));
663+
values.push(1);
664+
},
665+
});
666+
667+
const myOtherHandler = async () => {
668+
await handleSubmit();
669+
values.push(2);
670+
};
671+
672+
await myOtherHandler();
673+
674+
// This test case failed before fixing the bug, See top of this test case.
675+
expect(values).toEqual([1, 2]);
676+
});
677+
678+
it('returns a promise that only resolves when onSubmit resolves - with validation', async () => {
679+
// See test case above.
680+
const values = [];
681+
682+
const {handleSubmit} = createForm({
683+
validate: () => true, // Dummy validation just to make sure that code path is taken.
684+
onSubmit: async () => {
685+
await new Promise((resolve) => setTimeout(resolve, 10));
686+
values.push(1);
687+
},
688+
});
689+
690+
const myOtherHandler = async () => {
691+
await handleSubmit();
692+
values.push(2);
693+
};
694+
695+
await myOtherHandler();
696+
697+
expect(values).toEqual([1, 2]);
698+
});
653699
});
654700

655701
describe('validateField', () => {

0 commit comments

Comments
 (0)