React rendering component before ComponentWillMount function / setState not working

  axios, javascript, reactjs, setstate

I’m new to React and been struggling with my code and can’t find what I’m doing wrong,

This is my code

export class MainPage extends Component {

constructor(props){
    super(props);
    this.state = {
        pn_list : []
    }
}

componentWillMount() {
    axios.get('http://localhost:8080/pn_info/over_30')
    .then((response) => {
        this.setState(
            {pn_list : response.data}
            )
    })
}

render() {
    return(
        <div>
            <SelectionMenu data={this.state.pn_list}/>
        </div>
        )
    };
};

export default MainPage;

Basically my code is trying to render the SelectionMenu component before the componentWillMount finishes and I don’t get why this is happening. I tried to console.log(this.state.pn_list) after axios gets the response but it looks like the setState method is not updating it since it still logs the empty array. Can you guys give me a help please?

Source: Ask Javascript Questions

LEAVE A COMMENT