I'm working with React Hook Form. I have a higher order component that is using FormProvider and managing the submitting of the form. I want to trigger this function from a child component. The problem I'm having is that when I call the function in the child component the data in the onSubmit function returns undefined. However it works as expected when I click submit in the same component. What am I doing wrong?
const FormGroup = () {
const onSubmit: SubmitHandler<Inputs> = data => {
console.log('data', data);
dispatch(setEntityInformation({
data
}));
}
};
<FormProvider {...methods}>
<form onSubmit={methods.handleSubmit(onSubmit)}>
<section className="sars__sideBar">
<TabBar
controls={TAB_CONTROLS.controls}
activeIndex={index}
setActiveTab={i => setActiveTab(i)}
onSubmit={onSubmit}
/>
</section>
<PrimaryButton onClick={() => {
setActiveTab(index + 1);
}}
>
<input type="submit" value="Continue" /> // submits form as expected
</PrimaryButton>
</form>
</FormProvider>
}
// Child component
const TabBar = ({ activeIndex, setActiveTab, controls, onSubmit }) => (
<Tabs>
{controls.map((control, i) => (
<div
className={`tab__wrapper ${i === activeIndex ? 'active' : ''}`}
key={control.key}
onClick={() => {
setActiveTab(i);
if (i > activeIndex) {
onSubmit(); // function is called, but data is undefined
}
}}
>
<div className="u-alignCenter">
<p>{control.label}</p>
</div>
<div className="tab__status" />
</div>
))}
</Tabs>
);
Maybe calling onSubmit()
through handleSubmit
would help? Like this: handleSubmit(onSubmit)();
You need this, because handleSubmit is ran asynchronously and with the second parentheses you actually call the returned function.
You can read more about it here