简体   繁体   中英

Javascript saying object value is undefined. What am I doing wrong?

I'm trying to display the value of an object within an array of Github repositories (retrieved from a parsed JSON) in my React app but I'm getting an error that the browser can't read property key of undefined.

I'm able to console.log the JSON data and the objects within it but if I try to log the values within those objects, I get the error.

const App = () => {
const [repoList, setRepoList] = useState({});

useEffect(() => {
    fetch("https://example.com/api")
        .then(res => res.json())
        .then(data => setRepoList(data));
});

return (
    <div>{repoList[0].id}</div>
)

}

If I put JSON.stringify(repoList) within the div element, it shows the data.

If I put JSON.stringify(repoList[0]) within the div element, it also shows the data.

But if I put something like repoList[0].id nothing appears. This happens with each key listed. And I can confirm that the key is there. What am I doing wrong?

You're calling async functions to populate the repo list. The first time the return tries to use repoList[0].id , there is no repoList[0] . You may want to initialize repoList to a non-error-ing dummy object when you set it up with useState({})

Try this.

const [repoList, setRepoList] = useState([]); // Change to array not object.

...

return repoList.length ?
  (<React.Fragment>{repoList[0].id}</React.Fragment>) 
  : (<span>Loading ....</span>)

If your div does not have styles, better user Fragment , it result in better performance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM