Reputation: 21
I have this link https://api.covid19api.com/countries, which holds the "Country", "Slug", and "ISO2" of several countries. I want to display, only the "Country" value in tag.I wrote the following code
function App() {
const [countries,setCountries] = React.useState();
React.useEffect(()=>{
async function fetchData(){
const data = fetch('https://api.covid19api.com/countries').then(resp => resp.json());
setCountries(data)
}
fetchData();
},[])
if(!countries){
return(
<h3>Loading.....</h3>
)
}
return (
<div>
{
countries.map(() => <h1>{countries.Country}</h1>)
}
</div>
);
}
export default App;
but, it was giving the following error
TypeError: countries.map is not a function
Could anyone please say the correct way to do it
Upvotes: 0
Views: 76
Reputation: 169
You have had await keyword with async. The word 'async' before a function means one simple thing: a function always returns a promise and the keyword await makes JavaScript wait until that promise settles and returns its result. So it will be something like this
React.useEffect(() => {
async function fetchData() {
const data = await fetch("https://api.covid19api.com/countries").then(
resp => resp.json()
);
setCountries(data);
}
fetchData();
}, []);
This is my codesandbox link if wanna check - https://codesandbox.io/s/cocky-lewin-7wwn9
Upvotes: -1
Reputation: 3333
3 issues
1 => You are not using await
2 => You are not passing any parameter in the map method
3 => Response is an array, So you need to make your state an array.
Updated Code.
function App() {
const [countries,setCountries] = React.useState([]);
React.useEffect(()=>{
async function fetchData(){
const data = await fetch('https://api.covid19api.com/countries').then(resp => resp.json());
setCountries(data)
}
fetchData();
},[])
if(!countries){
return(
<h3>Loading.....</h3>
)
}
return (
<div>
{
countries.map((data) => <h1>{data.Country}</h1>)
}
</div>
);
}
export default App;
Upvotes: 2
Reputation: 5225
I think you're just missing an await
before setCountries
.
const data = await fetch('https://api.covid19api.com/countries').then(resp => resp.json());
setCountries(data)
Also, I think, it's better to initialise countries
with an empty array here in this case.
const [countries,setCountries] = React.useState([]);
Upvotes: 2