I have a parent component that has a state of its own and that is shared across the child components as well.
In my child component, I have a form and for the data, I've created a local state. Let's call this child component .
In my parent component, there is a button on click of which I update the data from my child's local state to my parent's state. This I do by passing a flag from parent to child.
Also my parent renders the same child twice making the final code like this:
const parent = () => {
const [parentState, setParentState] = useState(null);
const [submitSignal, setSubmitSignal] = useState(false);
const handleSave = () => {
setSubmitSignal(true);
}
return (
<div>
<div onClick={handleSave}>
Save Data
</div>
<Child
pos={0}
key={0}
parentState={parentState}
submitSignal={submitSignal}
setParentState={setParentState}
/>
<Child
pos={1}
key={1}
parentState={parentState}
submitSignal={submitSignal}
setParentState={setParentState}
/>
</div>
)
}
const Child = (props) => {
const [childState, setChildState] = useState(null);
React.useEffect(() => {
const { pos, submitSignal, parentState, setParentState } = props;
if (submitSignal) {
setParentState(...parentState, ...childState);
}
}, [props.submitSignal])
return (
<div>
// A large form which multiple fields
</div>
)
}
Now what's happening here is as soon as I make the submitSignal true from my parent component both the child receive it at the same time and try to update the parent's state. It's kind of a race condition situation where Child 0 updates the data but before it's even get updated in parent state Child 1 also updates the parent's state and thereby overwriting/removing what Child 0 added.
Please help me out with this.
P.S: The reason why I have gone with this structure is that in my Child I have a very large form and the same form is used twice.