I am trying here to pass the data received from EDIdata.json to child component . But at first place, the data is not being fetched from the API as getData() is not invoked on page load.
I want to pass the data fetched from EDIdata.json to child component MilestoneSummary. But the console.log under this component log ‘undefined’ as at first place the API to get the data from json file is not invoked.
import { React, useEffect, useState } from 'react';
import MilestoneSummary from './MilestoneSummary';
import { Grid, Column } from '@carbon/react';
const OrderSummary = () => {
const [data, setData] = useState({ data: {} });
useEffect(() => {
getData()
})
const getData = () => {
fetch('EDIData.json'
, {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
}
)
.then(function (response) {
console.log("JSON response" + response)
return response.json();
})
.then(function (myJson) {
setData(myJson)
})
.catch(err => { console.log(err) })
}
console.log(data);
return (
<>
<Grid>
<Column md={4} lg={4} sm={4}>
<h3 className="landing-page__label">Order milestone summary</h3>
<MilestoneSummary summaryItems={data.OrderMilestoneSummary} />
</Column>
</Grid>
</>
)
};
export default OrderSummary;
2
Answers
When using the useEffect hook, you must pass a dependency array as an argument at the end.