Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

how to call rest 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;
Comment

PREVIOUS NEXT
Code Example
Javascript :: js check if variable is string 
Javascript :: $(this).text() in jquery return white space 
Javascript :: remove duplicates in json array based on two fields in lodash 
Javascript :: dynamically change css class with javascript 
Javascript :: Package path ./compat is not exported from 
Javascript :: get previous url angular 
Javascript :: javascript iterate over divs 
Javascript :: import file json angular 12 
Javascript :: javascript getminutes 2 digits 
Javascript :: vs code open file in new window 
Javascript :: This is the RegEx for Roman numerals 
Javascript :: string contains substring javascript 
Javascript :: custom event handler javascript 
Javascript :: svg to string javascript 
Javascript :: get text from selected select javascript object 
Javascript :: react material ui classname 
Javascript :: createrouter vue history remove Hash 
Javascript :: js remove element from array 
Javascript :: on change field text jquery 
Javascript :: check if all elements in array are true javascript 
Javascript :: es6 create array with increasing number 
Javascript :: convert file to blob javascript 
Javascript :: javascript cookies store object 
Javascript :: lodash sumby 
Javascript :: javascript toutcstring 
Javascript :: react native tab.screen hide title 
Javascript :: toaster for angular 
Javascript :: js delete element 
Javascript :: assign class to element javascript 
Javascript :: select element as role in jquery 
ADD CONTENT
Topic
Content
Source link
Name
1+9 =