skip to Main Content

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


  1. When using the useEffect hook, you must pass a dependency array as an argument at the end.

    useEffect(() => {
        const fetchDat`enter code here`a = async () => {
            try {
                const response = await fetch('https://example.com/api/data');
                const json = await response.json();
                setData(json);
            } catch (error) {
                console.error('Error fetching data:', error);
            }
        };
    
        fetchData();
    }, []); // <-- pass empty array as second argument
    
    Login or Signup to reply.
  2.     First, if you don't pass dependency to useEffect it will run on each state update. when using the useEffect hook, make sure to provide a dependency array that includes all the variables that the effect depends on.
    
        For example, if you only want the effect to run once when the component mounts /loads, you can pass an empty dependency array like this:
    
             useEffect(() => {
              // effect code here
            }, []);
    
        If you want the effect to run whenever a specific variable changes, you can include that variable in the dependency array:
    
            const [count, setCount] = useState(0);
    
            useEffect(() => {
              // effect code here
            }, [count]);
    
        Second, make sure you have your json file inside the public folder at the root of your project. 
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search