I’m just trying to implement a simple React project that retrieves data from an API and iterates over it to create table rows. I’m not getting any errors, but the data isn’t appearing in the table.
import { useEffect, useState } from 'react';
import './App.css';
function Countries() {
const [data, setData] = useState([]);
useEffect(() => {
fetch('https://restcountries.com/v3.1/all?fields=name,continents,population,flag')
.then((resp) => resp.json())
.then((apiData) => {
setData(apiData);
});
});
return (
<div className="app-container">
<table>
<thead>
<tr>
<th>Name</th>
<th>Continent</th>
<th>Population</th>
<th>Flag</th>
</tr>
</thead>
<tbody>
{data.map((country) => {
<tr>
<td>{country.name}</td>
<td>{country.continents}</td>
<td>{country.population}</td>
<td>{country.flag}</td>
</tr>
})}
</tbody>
</table>
</div>
);
}
export default Countries;
Still there are no errors so I’m not sure why the data isn’t appearing in the table.
Just returns a blank page.
Any help would be greatly appreciated.
2
Answers
You’re not returning anything from the map function inside the
tbody
tag. You need to add thereturn
keyword or use parentheses to wrap the JSX. Also pass an empty array as the second argument to runuseEffect
only once.You are not returning the render
tr
elements, because you wrapped them in curly brackets instead of parentheses. In addition,name
is an object, and you should usecountry.name.common
, andcountry.continents
is an array, and you should join it to a single string, or iterate the items:In addition, you the
useEffect
doesn’t have a dependencies array, which means that it would run on every state change (like setting the state), which would cause another api calls, and set state, which would lead to an infinite loop. Set an empty array[]
as the dependencies of youruseEffect
to prevent this.Example: