Reputation: 133
I am using React Hooks to access the Covid-19 data from this API. So far, I have successfully accessed: country and province
. But when I came at the confirmed, and death cases which are under the stats
I couldn't access those data
stats.confirmed
Here is my current code for the API data:
import React from "react";
import { useFetch } from "./Hooks";
function Data() {
const [data, loading] = useFetch("https://corona.lmao.ninja/v2/jhucsse");
return (
<>
{loading ? (
"Loading..."
) : (
<table>
<tbody>
<tr>
<th>Province</th>
<th>Country</th>
<th>Confirmed Cases</th>
<th>Recovered</th>
</tr>
{data.map(({ country, province, stats.confirmed }) => (
<tr>
<td>{province ? province : 'No province'}</td>
<td>{country}</td>
<td>{stats.confirmed}</td>
</tr>
))}
</tbody>
</table>
)}
</>
);
}
export default Data;
And this is the code for the Hook:
import { useState, useEffect } from "react";
function useFetch(url) {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);
async function fetchUrl() {
const response = await fetch(url);
const json = await response.json();
setData(json);
setLoading(false);
}
useEffect(() => {
fetchUrl();
}, []);
return [data, loading];
}
export { useFetch };
Upvotes: 1
Views: 166
Reputation: 13703
you need to remove the stats.confirmed from the object and just fetch stats. Now you will be able to access all the other properties from the
Stats object :
"stats":{
"confirmed":3,
"deaths":0,
"recovered":3
},
Code:
{data.map(({ country, province, stats }) => (
<tr>
<td>{province ? province : 'No province'}</td>
<td>{country}</td>
<td>{stats.confirmed}</td>
</tr>
))}
Upvotes: 1