4156
4156

Reputation: 400

Map is undefined in React

I am using fetch to get API data that I'm using to create a drop down that I will add routes too. I've done this a couple of times before but I used axios previously but I just wanted to get familiar with fetch as well. Can anyone see the problem of why map would be undefined?

import React, { Component } from 'react'

class Fetchheroes extends Component {
    constructor() {
        super();
        this.state = {
            heroes:  [],
        }
    }

    componentDidMount(){
        fetch('https://api.opendota.com/api/heroStats')
            .then(results => {
                return results.json();
            }).then(data =>{
                let heroes = data.results.map((hero) =>{
                    return(
                        <div key={hero.results}>
                             <select>
                                 <option>{hero.heroes.localized_name}</option>
                             </select>
                        </div>
                    )

                })
            this.setState({heroes: heroes});
            console.log("state", this.state.heroes);
        })
    }
    render(){
        return(
            <div>
                <div>
                    {this.state.heroes}
                </div>
            </div>
        )
    }

}
export default Fetchheroes

Upvotes: 0

Views: 66

Answers (1)

Piotr Glejzer
Piotr Glejzer

Reputation: 278

You have a bad mapping about data. You need to use data instead of data.result and you have a bad key value because results are not unique key in that case. You also don't need your hero.heroes.localized_name just hero.localized_name. I made an example in codesandbox.

https://codesandbox.io/s/clever-hodgkin-7qo6p

Edit

I made another example when I put all records to one select, not for multiple selects, maybe is that what you need or someone else :).

https://codesandbox.io/s/bold-grass-gv0wc

Upvotes: 1

Related Questions