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

160
Vistas
React array being returned with no data, but there is data within the array with inspect element

I am creating an array of objects in react which contain a name and colour (the colour is for the colour of the pointer on google maps). These objects look like this { name: "Ben", colour: "green" }.

The issue I am facing is when I run this code. For example, in my javascript file, I have this bit of code:

data.forEach((element) => {
  if (!names.has(element.person)) {
    names.add(element.person)
    keys.push({ name:element.person, colour:element.personColour })
  }
})

This loops through my data, which in this case are photos, and pulls out the name and a corresponding colour for that person. There are checks to ensure the person isn't a duplicate, also. At the top of the file, I define keys and names, keys as an array, and names as a set.

If I type a console.log() statement at the bottom of this code to print keys, the data is displayed in the console.

However, when I go to my react return statement to return my JSX, and I type {console.log(keys)}, I am returned this:

[]
--> 0: {name: 'Ben', colour: 'yellow'}
    1: {name: 'George', colour: 'pink'}
    2: {name: 'Jerry', colour: 'green'}
    3: {name: 'Jesus', colour: 'orange'}
    4: {name: 'Max', colour: 'purple'}
    5: {name: 'Tom', colour: 'blue'}
    length: 6
    [[Prototype]]: Array(0)

As you can see, I am shown an empty array, but with data inside, I cannot access it. I have tried to make it a promise and then resolve it, but I am returned a blank array.

I am fairly new to JS and React, so that any help would be much appreciated :)

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

it could be that data didn't finish downloading, you get the data in a useEffect than u do whatever u want with it

const [data, setData] = useState([])

useEffect(() => {
   setData(your fetched data method here)
}, []) //[] <-on page render

function x() {
   data.forEach((element) => {
      if (!names.has(element.person)) {
         names.add(element.person)
         keys.push({ name:element.person, colour:element.personColour })
      }
   })
}
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