Reputation: 663
In my current project (reactjs + react-hook-form) I have a component Parent that have Child components dynamically generated by a button (add child), each of generated children implements a form using react-hook-form.
Parent is the only one in charge of submitting the forms (and this cannot be changed)so for this I've created a ref in Parent and pass it to every child as prop, in Child I register the handleSubmit
function returned by useForm
to this ref:
const Parent = () => {
const childrenRef = useRef(new Map())
const onSave = () => {
const childrenHandlers = Array.from(childrenRef.current.values())
const submissionProms = childrenHandlers.map(async (handleSubmit) => {
return handleSubmit(async (childData) => await callApi(childData))()
})
await Promise.all(submissionProms);
}
return {
<div>
<button>Add Child</button>
<button onClick={() => onSave()}>Save changes</button>
{
childrenFromSomewhere.map(childData => (
<Child
childData={childData}
childrenRef={childrenRef}
/>
))
}
</div>
}
}
const Child = ({childData, childrenRef}) => {
const { handleSubmit } = useForm(initiaState)
useEffect(() => {
childrenRef.current.set(childData.id, handleSubmit)
}, [])
return <some jsx>
}
This works just fine, only problem is that Parent needs to be aware of modified children and unmodified children so I doesn't make an api call for every child always but only the ones that have changed. So basically I need to pass the isDirty
prop from every children along with the handleSubmit function.
And here is when I'm lost, if instead of passing the handleSubmit function a I'm doing now I pass an object with the handleSubmit and the isDirty prop then neither the function nor the isDiry prop keep up to date anymore, that is the handleSubmit function always send default data no matter what, so passing an object as ref doesn't work.
Upvotes: 0
Views: 27