Zhao Yi Zhao Yi - 1 year ago 118
React JSX Question

Where to make http request on react component

Component is a key concept on reactjs. It renders the dom element based on its state or props. My case is that a component needs to render some values which are from http response. I don't know where I should call the http request method during component lifecycle. Should I call the http request on componentWillMount() method? Since the http request is async call, it will not stop the component lifecycle process. How to handle that the component render method is called before the http response? Is there a better way to handle this situation?

Answer Source

You're hitting on a sensible spot since (in my experience) there is much room for improvement when it comes to handling async/external calls in react. The easiest (as in simplicity or low complexity) way to do it is as you said, in componentWillMount.

Despite when/where the http request gets fired, a common pattern is to render a spinner until componentWillUpdate decides there is enough data to render the actual component.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download