React cannot read property map of undefined

Cannot read property ‘map’ of undefined, Why?

Because this.state is initially {}, and contacts of {} will be undefined. Important point is, componentDidMount will get called after initial rendering and it is throwing that error during first rendering.

Possible Solutions:

1- Either define the initial value of contacts as [] in state:

constructor(props) {
    this.state = {
       contacts: []

2- Or put the check before using map on it:

{this.state.contacts &&

For checking array, you can also use Array.isArray(this.state.contacts).

Note: You need to assign unique key to each element inside map, check the DOC.

Leave a Comment