TheProfiler
TheProfiler

Reputation: 277

Cannot read property 'map' of undefined with REACTJS

I am new with reactjs.

This is what I am trying

class EventDemo extends Component {
    constructor(){
        super()
        this.getStarWars()
        this.state = {}
    }

    getStarWars = ()=> axios.get('https://swapi.co/api/people')
        .then(res => {
            console.log(res.data)
            this.setState({
                names: res.data.results
            })

        })
    
    
    
    render() {
        console.log(this.state.names);
        
        return (
            <div>
                {this.state.names.map(function(e){
                    return <li>{e.name}</li>
                })}
            </div>
        );
    }
}

But This following error i am getting

error

What I am doing wrong here ? It supposed to work .

Upvotes: 4

Views: 1334

Answers (1)

Alessandro Messori
Alessandro Messori

Reputation: 1105

First of all,you shouldn't call your this.getStarWars() function inside the constructor, it is a very bad practice and could cause you troubles, http calls in React component should be generally called from the componentDidMount function.

However the issue in this case is another one,you haven't given an initial value to this.state.names, so when the component tries to do the initial render it fails because the names are undefined since the initial render appens before the http call is resolved

You code should be fixed like this:

class EventDemo extends Component {
    constructor(){
        super()
        this.state = { names:[] }
    }

   componentDidMount(){
      this.getStarWars()
   }


    getStarWars = ()=> axios.get('https://swapi.co/api/people')
        .then(res => {
            console.log(res.data)
            this.setState({
                names: res.data.results
            })

        })



    render() {
        console.log(this.state.names);

        return (
            <div>
                {this.state.names.map(function(e){
                    return <li>{e.name}</li>
                })}
            </div>
        );
    }
}

Upvotes: 2

Related Questions