简体   繁体   中英

Printing JSON data in React JS through mapping

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

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([]);

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;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM