I managed to fetch API and could output some data in browser, but I couldn’t handle an array of object in JSON. It’s a rest country API, where some countries have more than 1 language. I want to output all languages they speak. Here is the API link. And here is my code
import React, { useState, useEffect } from "react";
import CountryListCard from "./CountryListCard";
import "./CountryList.scss";
export default function CountryList() {
const [data, setData] = useState([]);
const fetchData = () => {
fetch("https://restcountries.eu/rest/v2/all")
.then((res) => res.json())
.then((result) => setData(result))
.catch((err) => console.log("error"));
};
useEffect(() => {
fetchData();
}, []);
return (
<div>
{data &&
data.map((element, index) => (
<CountryListCard
image={element.flag}
name={element.name}
key={index}
region={element.region}
population={element.population}
{/* language={element.languages[0]} this doesn't work*/}
/>
))}
{/* {data.languages &&
data.languages.map((element, index) => (
<CountryListCard key={index} language={element.languages.iso639_1} /> this doesn't work
))} */}
</div>
);
}
Advertisement
Answer
you should call the languages map inside your country map like:
countries.map(country=>(
<div key={country.name}>
<h1>{country.name}</h1>
{country.languages.map((language, languageIndex)=>(
<p key={languageIndex}>{language.name}</p>
))}
</div>
))
Also, it is not related with the post, but I’ll suggest you to not use generic names in your .map like item/element/obj