Home > other >  React async API call
React async API call

Time:12-17

I'm trying to understand somebody else code, I have this component:

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

export default function CountriesList({ searchValue }) {
  const [data, setData] = useState([])

  //Onmount
  useEffect(() => {
    async function init() {
      //API Calls- request data from the server
      const response = await fetch('https://restcountries.com/v2/all');
      const body = await response.json();
      setData(body);
    }
    init()
  }, [])//dependencies array
  return (
    <div className="countries-container">
      {data
        .filter(country => country.name.toLowerCase().includes(searchValue.toLowerCase()))
        .map((country) => {
          const { name, flag } = country;
          return (
            <div key={name} className="country-container">
              <h3 className="title">{name}</h3>
              <img src={flag} height="100px" width="100px" alt="flag" />
            </div>
          )
        })}
    </div>
  )
}

inside init(), the programmer call init() again, can you explain why? I tried to look for this style of programming and I didn't find anything. whiteout this line the API call doesn't work.

thank you!

CodePudding user response:

I may be mistaken, but as far as I can see, init function is declared and called right after declaration.

Check this out: https://github.com/facebook/react/issues/14326

CodePudding user response:

The call to init is placed after its declaration, not inside. This is the declaration of the function:

async function init() {
  //API Calls- request data from the server
  const response = await fetch('https://restcountries.com/v2/all');
  const body = await response.json();
  setData(body);
}

And right after that is the call to that function: init()

  • Related