Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do render only after http request completed in ReactJS

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

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 open page the render function is invoked before componentDidMount completed. Always returning function from else condition (renderNotValidateCompany) and returning renderValidateCompany after updating this.state.company.

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

Is it possible that rendering is called only when componentDidMount is completed in react?

Thanks!

like image 672
Renan Lalier Avatar asked Aug 22 '17 03:08

Renan Lalier


1 Answers

Like i said in a comment, store request status in the state and render based on it:

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

And in render 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*/}
 }
}

Ofcourse update request status in the Promise.

like image 128
Jan Ciołek Avatar answered Sep 24 '22 00:09

Jan Ciołek