John James
John James

Reputation: 287

Type Error, cannot read property 'map' of undefined

I'm reading data in from an API and I'm trying to have the elements in the data array show up in a select tag in HTML using React, but it keeps telling me that the data is not an array even though it seems like it is when I do console.log.

render(){
        console.log(this.state.countries.Countries)
        return(
            <div className = "tables-container">
                <h1>Tables</h1>
                <label>Please Select a Country to view data for:  </label>
                <select name = "countries" id = "countries">
                    <option selected = "selected">Select a Country</option>
                    {
                        this.state.countries.Countries.map((data)=>(
                             <option>{data.Country}</option>
                        ))
                    }
                </select>
            </div>
        )
    }

When I run this, it says "TypeError: Cannot read property 'map' of undefined." The console.log result reads

(188) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, …]

so I'm pretty sure this.state.countries.Countries should be an Array, so the map function should work, but it doesn't. In my constructor I have

this.state = {
    countries: [],
}

and I have the API fetch in

    componentDidMount(){
        fetch("https://api.covid19api.com/summary")
            .then((data) => data.json())
            .then((data) => {
                this.setState({
                    countries: data
                })
            })
    }

I've been stuck on this for an hour now I really need help figuring it out. Thanks!

Upvotes: 1

Views: 77

Answers (1)

Nicholas Tower
Nicholas Tower

Reputation: 85161

this.state = {
    countries: [],
}

this.state.countries starts off as an empty array. It has no .Countries property on it, so for your first render, this.state.countries.Countries is undefined, and you can't map undefined.

You need your state to have the same shape before and after you load data. So if you want the .countries.Countries nesting, change your initial state to this:

this.state = {
  countries: {
    Countries: []
  }
}

If you just want one level of nesting, keep your initial values and change the following:

// In componentDidMount
this.setState({
  countries: data.Countries
})

// In render
this.state.countries.map(

Upvotes: 1

Related Questions