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
JavaScript
x
42
42
1
import React, { useState, useEffect } from "react";
2
import CountryListCard from "./CountryListCard";
3
4
import "./CountryList.scss";
5
6
export default function CountryList() {
7
const [data, setData] = useState([]);
8
9
const fetchData = () => {
10
fetch("https://restcountries.eu/rest/v2/all")
11
.then((res) => res.json())
12
.then((result) => setData(result))
13
.catch((err) => console.log("error"));
14
};
15
16
useEffect(() => {
17
fetchData();
18
}, []);
19
20
return (
21
<div>
22
{data &&
23
data.map((element, index) => (
24
<CountryListCard
25
image={element.flag}
26
name={element.name}
27
key={index}
28
region={element.region}
29
population={element.population}
30
{/* language={element.languages[0]} this doesn't work*/}
31
/>
32
))}
33
{/* {data.languages &&
34
data.languages.map((element, index) => (
35
<CountryListCard key={index} language={element.languages.iso639_1} /> this doesn't work
36
))} */}
37
</div>
38
);
39
}
40
41
42
Advertisement
Answer
you should call the languages map inside your country map like:
JavaScript
1
9
1
countries.map(country=>(
2
<div key={country.name}>
3
<h1>{country.name}</h1>
4
{country.languages.map((language, languageIndex)=>(
5
<p key={languageIndex}>{language.name}</p>
6
))}
7
</div>
8
))
9
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