user17422
user17422

Reputation: 383

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 
    }

   }

Upvotes: 0

Views: 2649

Answers (2)

Fez Vrasta
Fez Vrasta

Reputation: 14815

If you make the ajax request inside the parent component, you can just tell React to not render the table if the needed data is not ready:

render() {

  const table;
  if (this.state.data) table = <table data=this.state.data />;

  return table;
}

A note looking at your code: never do:

this.setState({ foo: '' });
this.setState({ foo: 1 });

setState is async, so you may end up having foo as '' instead of 1

Upvotes: 0

John
John

Reputation: 2894

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>
    )

}

Upvotes: 1

Related Questions