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

134
Vistas
Is this the wrong way of handling array of objects from api call?

I am trying to store a array of names from a json response containing an array of objects.

For some reason the printing array will have nothing inside.Is this the correct way of doing it. Its not working for some reason otherwise no errors.

also the forEach is loop not even running once i tested it.


useEffect(() => {
  
    instance.get('/')
    .then(function (response) {
      // handle success
      //console.log(response);
      console.log(response.data);
      (response.data).forEach(newValue=>
        {
          setArray(oldArray => [...oldArray,newValue.name])
        }
      )
    })
    .catch(function (error) {
      // handle error
      console.log(error);
    })
    .then(function () {
      console.log("printing array 1",Array);
      // always executed
    });
    
    if(Array)
    console.log("printing array 2",Array);
    
  },[]);
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Try this:

setArray([...oldArray, ...response.data?.map(item=>item.name)]);

Rather than updating your state for every item in the new array, just get all the name props as an array from the new array using map and then use the spread operator to combine both new and old arrays.

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