Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
Ask Question
After updating the state of the component with the promise from a
fetch call, I am unable to access the properties of the object.
When I console.log the object I see it but when I try to access
the property it throws a Type error: Cannot read property 'name'
of undefined.
I have tried console.log(Object.keys(filteredStudents[0])) and i
TypeError: Cannot convert undefined or null to object
class App extends React.Component {
constructor(prop){
super(prop)
this.state = {
searchField: '',
students: [],
menu: 'home'
componentDidMount() {
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => {
return response.json()
}).then(data => {
// console.log(data);
this.setState({students: data})
}).catch(err => console.log('error', err))
render (){
```````````````````````````````````````````````````````````
const filteredStudents = this.state.students
console.log(filteredStudents[0])
console.log(Object.keys(filteredStudents[0]))
````````````````````````````````````````````````````````
I expect the output to return the value of any key I try to
access. e.g
console.log(filteredStudents[0].name) -----> 'leanne'
You are trying to access the items in the fiteredStudents array before the promise has had a chance to resolve and before your state has been updated. If you wrap your logic inside of a conditional, i.e.
if(filteredStudents.length) {
console.log(filteredStudents[0])
console.log(Object.keys(filteredStudents[0]))
Then it should work.
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.