I have a complex form in React containing a dozen sub-components. It also includes my own form components that operate by not single values. Some parts of the form use trees of objects as data.
I have the main component (let's call it EditForm) which stores the whole object tree of data. I assume each component of this form should use a specific part of this main object. I should have the ability to store whole form data into JSON and read it back from JSON (and update all sub-components automatically when JSON changed).
The idea was to refresh only those parts of the form that required when I change the main JSON. But the code which handles this behavior is dramatically big and complex. I have to implement comparison functionality into each sub-component and also transfer parts of the main JSON into props of each sub-component.
const [testobj, setTestobj] = useState({'obj1': {......}, 'obj2': {.......}, .......});
function revalidateSub(sub_name, value)
{
let t2 = cloneDeep(testobj);
t2[sub_name] = value;
setTestobj(t2);
}
return (<MySubComponent subobj={testobj['sub1']} ident={"sub1"} onUpdateData={v => revalidateSub('sub1', v)}/>)
(subobj
is the piece of data which is controlled by a specific sub-component, onUpdateData
is a handler which is called inside the subcomponent each time when it makes any changes to a controlled piece of data)
This scheme, however, does not work as expected. Because revalidateSub() function stores its own copy of testobj and onUpdateData of each component rewriting the changes of other sub-components...
To be honest, I don't quite understand how to store data correctly for this type of React apps. What do you propose? Maybe I should move the data storage out of React components at all? Or maybe useMemo?
Thank you for the shared experience and examples!
Update1: I have coded the example in the Sandbox, please check https://codesandbox.io/s/thirsty-browser-xf4u0
To see the problem, please click some times to the "Click Me!" button in object 1, you can see the value of obj1 is changing as well as the value of the main object is changing (which is CORRECT). Then click one time to the "Click Me!" of the obj2. You will see (BOOM!) the value of obj1 is reset to its default state. Which is NOT correct.