Pol Grisart
Pol Grisart

Reputation: 179

React - wait the end of a request using Superagent

In ComponentWillMount I am fetching data from Node.js using Superagent.

  componentWillMount() {
    request.get("/appData").end((error, response) => {
      if (!error && response) {
        this.setState({ dataJSON: response.body });
      } else {
        console.log("There was an error fetching server", error);
      }
    });
  }

This data is saved in this.state.dataJSON in order to render it in the render().

The problem is the render() is called before the setState() is effective. But once the setState() updates the state of dataJSON the render is called a second time and render the data.

So I'm asking you a solution to wait for the update of dataJSON in order to call the render only when dataJSON is updated.

Upvotes: 0

Views: 922

Answers (1)

AKX
AKX

Reputation: 169268

There is no such thing as delaying renders in React (... yet).

There're two things you can do:

  • load that state in the parent component and only mount the subcomponent when you have the data
  • make the illustrated component's render() check whether it's still loading and either show a loading message or return null if it's not ready.

Upvotes: 1

Related Questions