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

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

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 Denunciar

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 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