Search
 
SCRIPT & CODE EXAMPLE
 

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;
Comment

PREVIOUS NEXT
Code Example
Javascript :: Fibonacci Series Program. in javascript 
Javascript :: useref array of refs 
Javascript :: laravel jquery csrf 
Javascript :: React Hook "React.useState" is called in function "placeItem" which is neither a React function component or a custom React Hook function react-hooks/rules-of-hooks 
Javascript :: how to do radio button validation in jquery 
Javascript :: While loop factorial function in javascript 
Javascript :: get highest value in array of object javascript 
Javascript :: getting state in react-router-dom v6 
Javascript :: javascript check if a number is even or odd 
Javascript :: javascript change paragraph text 
Javascript :: Glide Ajax Client Script ServiceNow 
Javascript :: string contains string javascript 
Javascript :: nodejs check if string matches regex 
Javascript :: javascript Capitalise a String 
Javascript :: check if document is ready js 
Javascript :: conditional field validation with Yup 
Javascript :: how to remove middle characters in string javascript 
Javascript :: jquery on change 
Javascript :: set dropdown in jquery 
Javascript :: react router last page 
Javascript :: javascript fill array from 0 to n 
Javascript :: javascript get parent element height javascript 
Javascript :: how to store an entire object in cookies javascript 
Javascript :: javascript websocket 
Javascript :: js draw circle 
Javascript :: mysql json search array of objects 
Javascript :: append array js 
Javascript :: how to double array data in js 
Javascript :: class element in javascript 
Javascript :: jest enzyme test receive submit 
ADD CONTENT
Topic
Content
Source link
Name
5+6 =