I have parent component and multiple child components. Each child component is responsible of getting the data and binding to the object present locally.
Now in parent component, i have save method. When save click event is triggered, i need to collect all the objects from the child and map to a single object and pass to api. Can any one please help me how to do this?
Some methods which i tried but couldn't get succeeded is given below. I used useRef here.
// One of the child component
const Questionnaire = forwardRef((props,ref) => {
useImperativeHandle(ref, () => ({
getUserEnteredObjectRef() {
return userEnteredData;
}
}));
});
//in my parent
function HandleSaveRequest() {
console.log('Save Request Command:');
let qtnObj = questionnaireRef.current.getUserEnteredObjectRef(); // prints the object
console.log(qtnObj); // displays the object from the child
setSaveRequestObj({qtn:qtnObj}); // don't get assigned and the object will be empty. strange is when i click the save 2nd time i get the object assigned.
axios.post(API, SaveRequestObj).then(res => {
goToDashboard();
}).catch(err => {
console.log('Error while saving' + err.message);
});
}
Reference Call child method from parent