Search code examples
reactjsrequeststatewaitsuperagent

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.


Solution

  • 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.