-
Using Mantine's Form hook. I am watching every form's field with const submitForm = useDebouncedCallback(
form.onSubmit((values, someInfoFromTheCaller) =>
generate(values as OpConfig, someInfoFromTheCaller),
),
500,
);
['specialField'].forEach((path) => {
const someSpecialInfo = 'someSpecialInfo';
form.watch(path, () => submitForm(someSpecialInfo));
});
['otherField1', 'otherField2'].forEach((path) => { // BTW is that the right way? I havent found a `submitOnChange` feature
form.watch(path, () => submitForm());
}); Because // Of course it could have been much simpler by forcing TS's hand e.g. ` { moveToComposedView: true } as unknown as FormEvent<HTMLFormElement>`, but bypassing TS is not always advisable.
export class MyFormEvent extends Event implements FormEvent<HTMLFormElement> {
public currentTarget: EventTarget & HTMLFormElement = {} as EventTarget & HTMLFormElement;
public target: EventTarget & HTMLFormElement = {} as EventTarget & HTMLFormElement;
public nativeEvent = this;
public isDefaultPrevented = (): boolean => true;
public isPropagationStopped = (): boolean => true;
public persist = (): void => {};
public readonly moveToComposedView: boolean; // The actual payload I want to carry across
constructor(config?: { moveToComposedView?: boolean }) {
super('submit');
this.moveToComposedView = config?.moveToComposedView ?? false;
}
}
// and then
const submitForm = useDebouncedCallback(
form.onSubmit((values, event) => generate(values as OpConfig, event as MyFormEvent)),
500,
);
['specialField'].forEach((path) => {
form.watch(path, () => submitForm(new MyFormEvent({ moveToComposedView: true })));
}); I feel dirty for forging such event, and I wish there were a better way. imho the issue comes from the fact that Is there a magic feature I may have missed, which would allow me to achieve this behavior in a canonical way ? Thanks :-) |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
form.onSubmit is designed to be used only with form element. You should call form.validate and your submit handler instead |
Beta Was this translation helpful? Give feedback.
-
Thank you, I think I understand now ; there is no centralized form submission feature, and we have to make our own const submitForm = useDebouncedCallback(
(values: FormValues, meta?: FormSubmitMeta) => generate(values, meta),
500,
);
const validateAndSubmit = (extra?: FormSubmitMeta) => {
const result = form.validate();
if (result.hasErrors) {
return;
}
submitForm(form.getValues() as FormValues, extra);
};
['specialField'].forEach((path) => {
form.watch(path, () => validateAndSubmit({ moveToComposedView: true }));
});
['otherField1', 'otherField2'].forEach((path) => {
form.watch(path, () => validateAndSubmit());
}); Am I getting this right? |
Beta Was this translation helpful? Give feedback.
form.onSubmit is designed to be used only with form element. You should call form.validate and your submit handler instead