I am very new to react and I am trying to bring in data from a rails api but I am getting the error TypeError: Cannot read property 'map' of undefined
If i use the react dev tools I can see the state and I can see the contacts if I mess around with it in the console using $r.state.contacts
Can someone help with what I have done wrong? my component looks like this:
import React from 'react';
import Contact from './Contact';
class ContactsList extends React.Component {
constructor(props) {
super(props)
this.state = {}
}
componentDidMount() {
return fetch('http://localhost:3000/contacts')
.then(response => response.json())
.then(response => {
this.setState({
contacts: response.contacts
})
})
.catch(error => {
console.error(error)
})
}
render(){
return(
<ul>
{this.state.contacts.map(contact => { return <Contact contact{contact} />})}
</ul>
)
}
}
export default ContactsList;
The "Cannot read property 'props' of undefined" error occurs when a class method is called without having the correct context bound to the this keyword. To solve the error, define the class method as an arrow function or use the bind method in the classes' constructor method.
How to Fix the Error? In order to fix the error, you need to make sure that the array is not undefined . In order to do this, the simplest way is to use optional chaining. You can use optional chaining by introducing a question mark after the variable.
There are 3 main reasons the "Cannot read properties of undefined" error occurs: Accessing a property on a variable that stores an undefined value. Accessing a property on DOM element that doesn't exist. Inserting the JS script tag above the HTML where the DOM elements are declared.
Usage in React To display it to the DOM, you need to use the map() function and return JSX from the callback function. This is the most common use case of the map() function in React. Other than rendering, the map() function can also be used in a utility function, which can be imported from another file.
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) {
super(props)
this.state = {
contacts: []
}
}
2- Or put the check before using map
on it:
{this.state.contacts && this.state.contacts.map(....)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With