Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 140817

How to map through api data in React?

$
0
0

Im building a app using a country api and which displays information such as name, population and region of a country. I want to display the languages, currencies and borders with the country. Ive tried to map the data to display the borders but it's saying map is undefined.

<div>
    // this works and displays
    <h1>{info.name}</h1>
    <p>Population: {info.population}</p>
    <p>Region: {info.region}</p>
    <p>Capital: {info.capital}</p>
    <h4>Languages:</h4> 
    // this gives the error 'cannot map of undefined'<ul>
        {info.borders.map((border) => {
          return <li key={border.name}>{border.name}</li>; })}
    </ul>
</div>

here is the response data i'm using

data:
name: "Brazil"
topLevelDomain: [".br"]
alpha2Code: "BR"
alpha3Code: "BRA"
callingCodes: ["55"]
capital: "Brasília"
altSpellings: (4) ["BR", "Brasil", "Federative Republic of Brazil", "República Federativa do Brasil"]
region: "Americas"
subregion: "South America"
population: 206135893
latlng: (2) [-10, -55]
demonym: "Brazilian"
area: 8515767
gini: 54.7
timezones: (4) ["UTC-05:00", "UTC-04:00", "UTC-03:00", "UTC-02:00"]
borders: (10) ["ARG", "BOL", "COL", "GUF", "GUY", "PRY", "PER", "SUR", "URY", "VEN"]
nativeName: "Brasil"
numericCode: "076"
currencies: [{…}]
languages: [{…}]

Below is how I'm getting the data

const Infopage = () => {
  const [info, setInfo] = useState({});

  const code = useParams().alpha3Code;

  useEffect(() => {
    console.log('info');
    axios
      .get(`https://restcountries.eu/rest/v2/alpha/${code}`)
      .then((response) => {
        console.log(response);
        setInfo(response.data);
      });

    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (
    <div>
      <CountryInfo info={info} />
    </div>
  );
};
export default Infopage;

Ive tried this with the same issue

 const [info, setInfo] = useState({});
  const [isLoading, setIsLoading] = useState(false);

  const code = useParams().alpha3Code;

  useEffect(() => {
    const fetchData = async () => {
      setIsLoading(true);
      const result = await axios.get(
        `https://restcountries.eu/rest/v2/alpha/${code}`
      );
      setInfo(result.data);
      setIsLoading(false);
    };
    fetchData();
  }, [code]);

  return (
    <div>{isLoading ? <h1>Loading...</h1> : <CountryInfo info={info} />}</div>

Viewing all articles
Browse latest Browse all 140817

Latest Images

Trending Articles



Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>