0

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

Sanju Rao
  • 13
  • 2
  • Do you need to collect the data on pressing save, or would it make more sense to have an onChange callback on each of the child components? If you had an onChange callback for each component, then the parent could build up the object to save prior to submitting, rather than at submit-time. – Nick Howard Jul 14 '20 at 13:01
  • @NickHoward this is my last option, but i am trying to retrieve child object oly when i click save – Sanju Rao Jul 14 '20 at 14:03

1 Answers1

0

See refs doc:

You need to use current to access getUserEnteredObjectRef

let qtnObj = questionnaireRef.current.getUserEnteredObjectRef(); 

See a demo here

gdh
  • 13,114
  • 2
  • 16
  • 28
  • yes! i am using "current" sorry i missed it before, but when i set this to use state variable i don't see getting assigned. But the strange thing i observer was, when i click the save button twice object is getting assigned to the use state variable – Sanju Rao Jul 14 '20 at 14:01