Nested Forms #6362
-
|
Hi there, Thanks as always for the great library - I was wondering if there is any sensible pattern for nesting forms: The use case is as follows: we need to have an overarching <FormProvider mode="onSubmit">
<Form>
... various simple inputs
</Form>
<FormProvider mode="onChange">
</FormProvider>
</FormProvider>Out of the box there are a few issues with this
I've been attempting to engineer my own solution by adding a custom FormProvider and keeping track of It looks something like this const useSetupRootForm = (
methods: UseFormReturn<FieldValues>,
rootFormContext: RootFormContextType | null
) => {
const handleSubmit: UseFormHandleSubmit<FieldValues> = useCallback(
(rootOnValid, rootOnInvalid) => {
const children = rootFormContext?.childForms;
let onValid = rootOnValid;
const onInvalid = rootOnInvalid;
if (children) {
let numberOfValidChildForms = 0;
onValid = (data) => {
numberOfValidChildForms++;
if (numberOfValidChildForms === Object.keys(children).length) {
return methods.handleSubmit(rootOnValid, rootOnInvalid);
}
};
Object.values(children).forEach((childForm) => {
childForm.handleSubmit(onValid);
});
}
return methods.handleSubmit(onValid, onInvalid);
},
[methods, rootFormContext?.childForms]
);
return {
handleSubmit,
};
};I've been working on this convoluted solution for a few days, but it seems I've hit a dead end - as I feel that I am over-engineering this, so if anyone has any advice that would be great. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
|
Hey dude, I'm no expert (just another user) but this does sound a little like a code smell. Is the only reason for the nested forms to validate Either way, I feel like there's a better solution if you use a single form and try to control the parts of it, rather than nesting forms like this. It's not something I've seen in any of the examples. |
Beta Was this translation helpful? Give feedback.
Hey dude,
I'm no expert (just another user) but this does sound a little like a code smell.
Is the only reason for the nested forms to validate
onChangeinstead ofonSubmit? If so, then would it not make sense to manually call the validation on those fields manually as they change? I did something similar where I calltrigger()on a single field based on when another one changes.Either way, I feel like there's a better solution if you use a single form and try to control the parts of it, rather than nesting forms like this. It's not something I've seen in any of the examples.