Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

how to call web api with the useeffect hook in react

//simple useEffect usage to call web api
import { useEffect, useState } from "react";

function App() {
  return (
    <div className="App">
      <LoadCountries></LoadCountries>
    </div>
  );
}

function LoadCountries() {
  const [countries, setCountries] = useState([]);
  useEffect(() => {
    fetch("https://restcountries.com/v3.1/all")
      .then((res) => res.json())
      .then((data) => setCountries(data));
  }, []);
  return (
    <div className="countries">
      <h3>Total countries: {countries.length}</h3>
      {countries.map((country) => (
        <Country country={country}></Country>
      ))}
    </div>
  );
}

function Country(props) {
  const { name, capital, flags, region } = props.country;
  console.log(props.country);
  return (
    <div className="country">
      <h2>{name.common}</h2>
      <img src={flags.png} alt="" />
      <h2>Capital: {capital}</h2>
      <h2>Region: {region}</h2>
    </div>
  );
}

export default App;
 
PREVIOUS NEXT
Tagged: #call #web #api #useeffect #hook #react
ADD COMMENT
Topic
Name
5+4 =