I am trying to create a separate card dynamically for each element that I have fetched with React.
Being quite new to React, I am having this issue where I can't map each of my element so that I can use them in the html. The official error that I am getting is:
Cannot read property 'map' of undefined
Here is a link to my json data
This is my React code:
export class ZonePreviewMenu extends React.Component {
constructor(props){
super(props);
this.state = {
isLoading: true,
rooms: []
}
}
componentDidMount(){
this.fetchData();
}
fetchData(){
fetch("https://api.myjson.com/bins/r5pn2")
.then(response => response.json())
.then(data => console.log(data))
.then(data => {this.setState({data: data })})
.catch(error => console.log("parsing failed", error))
}
render(){
return(
<div className="zone-panel">
<h2> Zones </h2>
{ this.state.data.map((item, i) => {
console.log(item.name)
})
}
<div className="image-panel">
<div className="#">
<div className="icon-row-one">
<img src={thermoIcon}/> 21C
<button className="btn btn-default btn-circle btn-lg top-buttons"><img src={cameraIcon}/></button>
<button className="btn btn-default btn-circle btn-lg lights-button"><img src={lightsIcon}/></button>
</div>
<div className="icon-row-two">
<img src={peopleIcon}/> 60
</div>
</div>
</div>
</div>
);
}
}
This is the part where I get the error:
{ this.state.data.map((item, i) => {
console.log(item.name)
})
}
Question: Why am I getting this error and how can I create a card for each element of the posted JSON object.
.then(data => console.log(data))you make it so thatdatain.then(data => {this.setState({data: data })})isundefined, so you should remove that.roomsin the response is an object with array values where each object in those arrays have one property. You most likely want to turn that data into a flat array if you want to usemapon it in the render method.