Mbiplang Ardel
Mbiplang Ardel

Reputation: 690

How to fix 'Type Error: Cannot Read Property 'name' of undefined when trying to access properties of an object' in React

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 get: 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'

Upvotes: 3

Views: 1894

Answers (1)

Gabor Szekely
Gabor Szekely

Reputation: 1238

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.

Upvotes: 1

Related Questions