why we prefer to write header or api request or ajax code in componentDidMount not in componentWillMount

161 views Asked by At

why we prefer to write header or api request or ajax code in componentDidMount not in componentWillMount.

need simple and clear difference with example

2

There are 2 answers

2
Edgar Henriquez On BEST ANSWER

You should use componentDidMount() because you need the component to be rendered in order to populate it with the data that you're fetching from the API.

componentWillMount(){
   //Fetch API and set the State
}

render(){
   return(<div>{this.state.myData}</div>)
}

When componentWillMount() fires up the <div> hasn't been rendered yet (does not exist at the moment in the DOM).

When using componentDidMount() in the other hand. The render method runs first creating the <div> element in the DOM, after that then componentDidMount() runs, fetching the data, you set your state and that creates a re-render of the component. That's why we use componentDidMount() to fetch data from the API. you can find more information here.

caveat: You should validate the state so you don't get undefined the first time the component is render (without the data from the API).

0
dxtmhjn On

edgaromar90 the same case with constructor also. we usually set temporary state in constructor and constructor invokes before the initial render. both constuctor and willMount invokes before initial render, then why we are not using in componentWillMount