How to render only after http request is completed in ReactJS

I need the render function of my component to be called only after the request for the componentDidMount function is complete.

componentDidMount(){    
    let ctx = this;
    ApiService.get('/busca/empresa/pagina').then(function(response){
      if(response.data.empresa){
        ctx.setState({company:response.data.empresa});
        ctx.getProducts();
        ctx.verifyAuthentication();
      }
    }, function(error){
       Notification.error('HTTP Status: ' + error.response.status + ' - ' + error.response.data.mensagem);
    });
}

The problem is that when the page is opened, the render function is called before the componentDidMount component completes. Always return a function from else (renderNotValidateCompany) and return renderValidateCompany after updating this.state.company.

render(){
    if(this.state.company){
      return this.renderValidateCompany();
    }else{
      return this.renderNotValidateCompany();
    }
}

Is it possible that rendering is only called when the DidMount component is completed in response?

Thanks!

+6
source share
2 answers

As I said in a comment, save the status of the request in a state and draw on it:

this.state = {
  company:null,
  requestCompleted:false,
}

And in the rendering method:

render(){
 if(this.state.requestCompleted && this.state.company){
    return this.renderValidateCompany();
  }
 else if (this.state.requestCompleted){
    return this.renderNotValidateCompany();
  }
 else {
  return <LoadingGif />
  {/*or return null*/}
 }
}

Promise.

+1

, , Javascript.

:

  • 1: , .
  • 2:
  • 3: DidMount
  • 4: render.

, 3 - , , . PHP, , , placeholder , , . , html , . , - , .

?

  • - (loader) , , , , . @jan-ciolek .

  • API , , . , API, . props.

  • , , div, , , , API. setState, .

0

All Articles