Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

142
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda