user17422 user17422 - 4 months ago 11
Ajax Question

How to stop the component from rendering before ajax call is completed in reactjs

I have a parent component and child component.
In the parent component I have a form which takes name and phone no and when I press submit I want the parent component to pass these values as props to child.

In the child component I am using the props and making ajax call and then want to show the result as a table below the form

So initially I only want the form to be shown but when I put in values and press enter I want the table to be shown below the form

So how do I stop the rendering of child component until the ajax is complete?

My child component code is

class List extends React.Component{

constructor(props) {
super(props);
this.state = {

page: ''
};

getPageInfo(info)
{

var self=this;

var dataHasChanged = (this.props.info !== info)

if ( dataHasChanged ) {
this.setState({page: ''});

//some ajax .done(function(data){

if ( self.props.info === info ) {
self.setState({
page: data });
}

});
}
}

componentWillMount(){
this.getPageInfo(this.props.info);
}

componentWillReceiveProps(nextProps){
this.getPageInfo(nextProps.info);
}


render(){
//something
}

}

Answer

You will want a conditional render. In other words, check for some value in your component's state (perhaps this.state.page).. if it is not present (yet) then render either nothing, or perhaps some kind of 'loading' image or text. Then when it is there you can render the data you want.

something like:

render() {
    return (
        <div>
        {this.state.page ? 
            <div>{this.state.page.somedata}</div>
        :
            <div>Loading...</div>}
        </div>
    );
}

or even:

render() {
    if (!this.state.page) {
        return <div>Loading...</div>
    }
    return (
        <div>
            <div>{this.state.page.somedata}</div>
        </div>
    )

}