React fetch data in server before render

What you’re looking for is componentWillMount.

From the documentation:

Invoked once, both on the client and server, immediately before the
initial rendering occurs. If you call setState within this method,
render() will see the updated state and will be executed only once
despite the state change.

So you would do something like this:

componentWillMount : function () {
    var data = this.getData();
    this.setState({data : data});
},

This way, render() will only be called once, and you’ll have the data you’re looking for in the initial render.

Leave a Comment