3
votes

I am Working on a ReactJs project and I use formik in it.

I have 2 different components (parent and child).

Here is the example, I tried to pass the formik data from parent to child and I need to set parent formik values from child component.

Right now I face an error as my parent component call child and when the child updates parent value it will again call the child and goes in the infinite loop.

Parent.js

<GSTData gstData={this.props.gstDetails?.GstDetails} 
  amount={this.props.totalAmount}
  onInputControlChange={(Total, GstData) => {
    TotalBillAmount = Total;
    GstDetails = GstData;
    console.log('Total', TotalBillAmount)
    //setFieldValue('NetOutStanding', 1);
  }}
  values={values}
  setFieldValue={setFieldValue}
/>

Child.js

componentDidUpdate(){
  this.props.onInputControlChange((this.GSTTotal + this.props.amount), this.GstDetails);
  this.props.setFieldValue('NetOutStanding', (this.GSTTotal + this.props.amount));
}
1

1 Answers

1
votes

What's happening is that when you update the input it calls the parent with the value to set. The parent then passes that value back to the child as a prop, which the Child perceives as an update, which then tells the parent the value again..... thus infinite loop

I would try taking

this.props.setFieldValue('NetOutStanding', (this.GSTTotal + this.props.amount));

out of the componentDidUpdate in the child component and calling it from it's own function.(This means you'll also have to set the value of the input being passed in from the parent directly). That should break the cycle