Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

278
Views
React useState Infinite Loop

I have a component and fetch data from an API (https://restcountries.eu/rest/v2/all). It is an array of objects. I want to pass some of the info of that object to a state but it gets stuck in a loop.

function AllCountries() {
  const [countries, setCountries] = useState([]);

  fetch(`https://restcountries.eu/rest/v2/all`)
    .then((r) => r.json())
    .then((data) => {
      if (data!== undefined) {
        
          data.map((ob) => {
          setCountries(
            ...countries,{
            flag: ob.flag,
            name: ob.name,
            population: ob.population,
            region: ob.region,
            capital: ob.capital}
          );
        });
        //console.log(countries);
      } else {
        alert("Can´t Load Data");
      }
    });

  return (
    <div>PRUEBA</div>
    
  );
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

It needs to be wrapped in useEffect:

function AllCountries() {
  const [countries, setCountries] = useState([]);

  useEffect(() => {
    fetch(`https://restcountries.eu/rest/v2/all`)
        .then((r) => r.json())
        .then((data) => {
        if (data!== undefined) {
            
            data.map((ob) => {
            setCountries(
                ...countries,{
                flag: ob.flag,
                name: ob.name,
                population: ob.population,
                region: ob.region,
                capital: ob.capital}
            );
            });
            //console.log(countries);
        } else {
            alert("Can´t Load Data");
        }
        });
  },[]);

  return (
    <div>PRUEBA</div>
    
  );
}

Otherwise, the fetch will get executed every time the component is rendered.

Furthe reading: https://reactjs.org/docs/hooks-effect.html

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!