Paweł Adamski
Paweł Adamski

Reputation: 3415

ReactJS - AJAX call in componentWillMount

React documentation suggest to fetch initial data in componentDidMount function. For my it is not intuitive because we could do it sooner in componentWillMount (first function from React component life cycle). In general I think we should start AJAX calls us soon us possible so user doesn't have to wait for them. So why do we have to wait until component is rendered?

My questions are:

Upvotes: 0

Views: 1692

Answers (3)

David
David

Reputation: 1159

say you do AJAX on componentWillMount

componentWillMount(){
   this.serverRequest = $.get(...);
}

Now you have a pending AJAX request. Its a good practice to cancel this request when the component is unmounted

componentWillUnmount: function() {
    this.serverRequest.abort();
}

but lets say for whatever reason the component did not mount. you still have your pending ajax request which can not be cancelled anywhere (since component is not mounted, componentWillUnmount won't be reached) thus creating a memory leak.

If you had put the ajax request on componentDidMount you had a guarantee that the componentWillUnmount will fire since component is mounted allowing you to cleanup your request safely

Upvotes: 7

skay-
skay-

Reputation: 1576

Simply create the component when you have the data and pass it through props. Have the parent component (if you have one) to do the request.

Upvotes: 1

sha
sha

Reputation: 157

It depends on your task. for example I have used an ajax request in componentWillReceiveProps here. what is your concern exactly? what does your ajax?

Upvotes: 0

Related Questions