ZombieChowder
ZombieChowder

Reputation: 1204

Displaying Data with ReactJS - Cannot read property 'map' of undefined

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.

Upvotes: 1

Views: 57

Answers (1)

Khodor
Khodor

Reputation: 1006

React will first render before the fetch call is finished using the initial state. In your initial state there's no data.

Define data as an empty array in your initial state

constructor(props){
    super(props);
    this.state = {
        isLoading: true,
        rooms: [],
        data: []
   }
}

Upvotes: 1

Related Questions