React api calling and create same div by 'map' method

Viewed 41

I want to call api and generate div using data from api, but I don't know why this code is not working. It doesn't show anything on the page.

This is my code. countryArray is an object array, and it has property of population, name, continent, capital.

import React from 'react'

function Countries() {
    fetch("https://restcountries.com/v3.1/all")
    .then((response)=>response.json())
    .then((countryArray)=>{
      return (
        <div>
        {countryArray.map((country)=>(
            <div className="Country_wrapper">
            <div className="Flag_wrapper">
                
            </div>
            <div className="Explanation_wrapper">
                <h2>{country.name}</h2>
                <p>Population: {country.population}</p>
                <p>Region: {country.continents}</p>
                <p>Capital: {country.capital}</p>
            </div>
        </div>  
        ))}
        </div>
      )
    },
    (err)=>{
      console.log(err);
    })
 

  
}


export default Countries
3 Answers

You need to return a jsx element. The usual way of doing data fetching inside react component is to do it inside an effect.
A minimal example would be like this.

function Countries() {
    const [countryArray, setCountryArray] = useState([]);

    useEffect(() => {
        (async function () {
            const res = await fetch("https://restcountries.com/v3.1/all");
            const json = await res.json();
            setCountryArray(json)
        })()

    }, [])

    return (
        <div>
            {countryArray.map((country)=>(
                <div className="Country_wrapper">
                    <div className="Flag_wrapper">

                    </div>
                    <div className="Explanation_wrapper">
                        <h2>{country.name.common}</h2>
                        <p>Population: {country.population}</p>
                        <p>Region: {country.continents}</p>
                        <p>Capital: {country.capital}</p>
                    </div>
                </div>
            ))}
        </div>
    )
}

Ofc you should also take care of race conditions, errors, loading states, or use a library that does all this stuff for you and more like react query.

Check the documentation for more information, fetching data

You can't return jsx from fetch, that won't be rendered.

Use useState inside a useEffect to save the data, then return from the functinon itself

const {useState, useEffect} = React;

function Countries() {

    const [ data, setData ] = useState([])
    
    useEffect(() => {
      function getData() {
        fetch("https://restcountries.com/v3.1/all")
            .then((response) => response.json())
            .then((countryArray) => setData(countryArray)
        );
      };
      getData();
    }, [ ]);

    return (
        <div>
            {data.map((country)=>(
                <div className="Country_wrapper">
                    <div className="Flag_wrapper">

                    </div>
                    <div className="Explanation_wrapper">
                        <h2>{country.name.common}</h2>
                        <p>Population: {country.population}</p>
                        <p>Region: {country.continents}</p>
                        <p>Capital: {country.capital}</p>
                    </div>
                </div>
            ))}
        </div>
    )
}

          
ReactDOM.render(<Countries />, document.getElementById("react"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js"></script>
<div id="react"></div>

Demo takes quite some time to load, so here's a pic:

enter image description here

Hello there first of all you need save the api data in a state and then fetch the api in useEffect then you can use the api data in your react app

import React , {useState , useEffect}  from 'react';


function app() {
const [examples , setExamples] = useState([]);
 useEffect(() => {
 fetch('https://restcountries.com/v3.1/all')
 .then((res) => res.json())
 .then((data) => {
 setExamples(data);
 
 })
 .catch((err) => console.log(err));
},[]);

return(
<>
<div>
  {
examples.map((example) => (
  <div className="Country_wrapper">
        <div className="Flag_wrapper">
            
        </div>
        <div className="Explanation_wrapper">
            <h2>{example.name.official}</h2>
            <p>Population: {example.population}</p>
            <p>Region: {example.continents}</p>
            <p>Capital: {example.capital}</p>
        </div>
    </div>  
))
  }

</div>
</>

);
      
}

export default app

this code is working

Related