Reputation: 11
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 :)
Upvotes: 0
Views: 426
Reputation: 709
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 })
}
})
}
Upvotes: 2