4

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 .

1
  • 1
    Just add names: [] to the this.state object inside the constructor. Commented Mar 28, 2018 at 20:33

1 Answer 1

2

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>
        );
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

really appreciate the help
no problem! I had the same troubles as you when I first started out using react :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.