Foxtrot 1-5
Foxtrot 1-5

Reputation: 379

Display JSON child content to HTML table in Reactjs

Guys i know this already asked many times, but i still don't get how to solve my problem. So what i want to do is display some nested JSON data to HTML table.

So this is the JSON i fetch.

and this is my reactjs code:

 var [infectionData, setInfectionData] = useState({
    response: []

  });

 var [isLoaded, setLoaded] = useState(false);

 useEffect(() => {

    var fetchData = async () => {
        var url = "https://api.covid19api.com/summary";

        var result = await axios.get(url);
        var response = result.data

        response = Array(response);

        setInfectionData({ response: response });

        console.log(infectionData.response);

    }

    fetchData();
    setLoaded(true);

});

and this is the HTML table:

            <Table bordered hover className="mt-3 w-75">
                <thead>
                    <tr>
                        <th>Country</th>
                        <th>Total Infection</th>
                        <th>New Deaths</th>
                    </tr>
                </thead>
                <tbody>
                    {
                        infectionData.response.Countries.map((item) => (
                            <tr>
                                <td>{item.Country}</td>
                                <td>{item.TotalConfirmed}</td>
                                <td>{item.NewDeaths}</td>
                            </tr>


                        ))
                    } 
                </tbody>

            </Table>

Any idea how to solve this ?

Upvotes: 0

Views: 178

Answers (2)

Sagar Roy
Sagar Roy

Reputation: 443

You may try with this

    infectionData.response.Countries && infectionData.response[0].Countries.map((item) => (
                        <tr>
                            <td>{item.Country}</td>
                            <td>{item.TotalConfirmed}</td>
                            <td>{item.NewDeaths}</td>
                        </tr>


                    ))

Upvotes: 1

Tazo leladze
Tazo leladze

Reputation: 1489

Here are the Array constructor https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Array

response = Array(response); remove this line and everything will be good.

Or

infectionData.response[0].Countries.map((item) => (
                        <tr>
                            <td>{item.Country}</td>
                            <td>{item.TotalConfirmed}</td>
                            <td>{item.NewDeaths}</td>
                        </tr>


                    ))

Upvotes: 1

Related Questions