'Object.keys returns an empty array [duplicate]
My object has keys but Object.keys() unexpectedly returns a empty array.
I have the following code in my src/components/Projects.jsx
import React from 'react'
import {Cards} from "./Cards"
export const Projects = (props) => {
let starsCount = {};
const [returned,setReturned] = React.useState(false); //monitors if api has returned the data
fetch('https://api.github.com/users/USERNAME_HERE/repos', {
headers: {
'Accept' : 'application/vnd.github.v3+json'
}})
.then(response => response.json())
.then( data => {
for(let i=0;i < data.length;i++) {
//if name of repo is "repo0" or "repo1" or "repo2" then add it to
//object with total stars count as it key
// example :-
// starsCount = {"repo1" : 5, "repo2" : 9, "repo3" : 2}
if(data[i].name == "repo0" || data[i].name=="repo1"|| data[i].name == "repo2"){
starsCount[data[i].name] = data[i].stargazers_count;
}
}
setReturned(true);
})
.catch( error => console.error(error));
returned ? console.log(starsCount,"keys are -> ",Object.keys(starsCount)) : {};
return (
<>
// render loading screen until api returns data
{(returned) ? <Cards> : <Loading/>}
</>
)
}
This code logs the starsCount as expected but logs an empty array of keys.
Here's what it logs :
Object { "repo0" : 5, "repo1" : 9, "repo2":3} keys are -> Array []
I also tried using Object.getOwnPropertyNames() but with no luck.
What am I doing wrong?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
