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

214
Visualizações
Getting a list of items not only last list item gets rendered - React

I had a problem is that when I return some data from an API, add it to the state's array, I only get the last list item, even though it maps over more than 1 item.

const [items, setItems] = useState([]);
    
    const fetchData = ()=> {
          DataService.getEnergyDataList()
          .then(response => {
            response.data.map(res=>{
             setItems([...items, res.Voltage])
          });   
        }
        )
          .catch(e => {
            console.log(e);
          });
        
        }
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

The problem is that you're calling setItems repeatedly (in the map callback), reusing the original items and then supplying just one more. That sets up a bunch of state updates, only the last of which is kept.

Instead, use the array that map creates:¹

const fetchData = () => {
    DataService.getEnergyDataList()
    .then(response => {
        setItems([...items, ...response.data.map(res => res.Voltage)]);
    })
    .catch(e => {
        console.log(e);
    });
};

¹ Any time you find yourself writing map without using the array that map creates, it's incorrect. (More on my blog.) Figure out whether you need that array and either modify the code to use the array map returns, or change the map to some other looping mechanism.

about 4 years ago · Juan Pablo Isaza Relatório

0

The problem is you are setting item for each element in .map callback. If you want to append the new response to items, you can use the callback approach of setState, something like:

.then(response => 
     setItems(currentItems => [...currentItems, ...response.data.map(res=> res.votage))
    );

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