Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

279
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda