Search code examples
reactjsinfinite-loopreact-functional-component

In React, how to fix the infinite/loop data passing from the child component to parent react functional component


I'm using the prop to pass data from the child component to the parent functional component. Both are different js files. Whenever I use prop I'm getting the infinite/loop data passing from the child component. How should I resolve this?

This is making my React app unable to load properly and crash.
Despite using the below react functional component, I'm able to retrieve the data properly without a loop from the React Class component so I assuming is the CallAPI.js functional class issue

Child component: DropDownList.js
Something like below...

class DropDownList extends React.Component {

//--body
  render() {

    return (
      <div>
      <CallAPI age={27}/>
      </div>
    );
  }
}

export default DropDownList;

Parent Component: CallAPI.js
Something like below..

const CallAPI = () =>{ //create a CallAPI function
  
const [DPID, setText] = useState("");
const [Quote, setText1] = useState("");

let gcmpapi =
  "https://gcm.dellsvc/GCM.Order.API/api/v1/orders/"+ DPID +"/purchase-summary-with-details?countryCode=US"; // declare a variable to store the URL

const [finalprice,setGCMP1] = useState('');
const [totaltax,setGCMP2] = useState('');
const [ShippingAmount,setGCMP3] = useState('');
const [CostPrice,setGCMP4] = useState('');
const [MarginTotal,setGCMP5] = useState('');
const [ListPrice,setGCMP6] = useState('');
const [SellingPrice,setGCMP7] = useState('');
const [DiscountValue,setGCMP8] = useState('');

  const callgcmpapi = () => { //assign a variable for a call function
    Axios.get (gcmpapi).then(
      (response) => { //Success
      console.log(response);
      setGCMP1(response.data.Data.PurchaseSummary.PriceSummary.FinalPrice); // call the value from the multi-dimensional array
      setGCMP2(response.data.Data.PurchaseSummary.PriceSummary.TaxTotal);
      setGCMP3(response.data.Data.PurchaseSummary.PriceSummary.ShippingAmount);
      setGCMP4(response.data.Data.PurchaseSummary.PriceSummary.CostPrice);
      setGCMP5(response.data.Data.PurchaseSummary.PriceSummary.MarginTotal);
      setGCMP6(response.data.Data.PurchaseSummary.PriceSummary.ListPrice);
      setGCMP7(response.data.Data.PurchaseSummary.PriceSummary.SellingPrice);
      setGCMP8(response.data.Data.PurchaseSummary.PriceSummary.DiscountValue);
      })
  };

Infinite data loop: Please see the screenshot


Solution

  • You should call APIs in useEffect() hook, your api will be called when the component has mounted:

    Ex:

    useEffect(() => {
      (async() {
        const data = await fetch(...);
        // do something with the data 
      })
    }, []) // passing empty dependency for useEffect it should be called one time when component mounted `