Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait until AJAX call is finished before rendering React component

Let's say I have the following code:

componentDidMount() {
    $.ajax({
        type: 'GET',
        url: '/data/',
        dataType: 'text',
        success: function(response) {
            this.setState({data: response})
        }.bind(this)
    });
}

render() {
    let {rows} = this.state.data
    return (
            <div>
                WOW
                {this.state.data}
                <FilterTable rows = {this.state.data} />
            </div>
        );
}

How can I make it so that the render() portion does not execute till ajax call is done?

Thanks!

EDIT: Fixed code.

like image 821
Lawrence Vo Avatar asked Feb 12 '26 11:02

Lawrence Vo


2 Answers

I would rather choose a very simple approach. I will have a state named for example 'show' set value to false initially. and after the successfull ajax return in the callback will set the value of 'show' to true. and in the render mount the jsx code in the return based on the value of 'show'.

componentDidMount() {
    $.ajax({
        type: 'GET',
        url: '/data/',
        dataType: 'text',
        success: function(response) {
            this.setState({data: response, show: true});
        }.bind(this)
    });
}

render() {
    let {rows} = this.state.data
    return (
            <div>
                WOW
                {this.state.show === true : <div>
                  {this.state.data}
                  <FilterTable rows = {this.state.data} />
                </div>: null
                }

            </div>
        );
}
like image 193
Rafi Ud Daula Refat Avatar answered Feb 15 '26 00:02

Rafi Ud Daula Refat


I am assuming you want to render the component only when the data is received . The below code snippet renders that component in the success of the ajax call. React has functions that allow us to mount a component in the DOM dynamically. You will need to import react-dom.

import ReactDOM from 'react-dom';

componentDidMount() {
  $.ajax({
    type: 'GET',
    url: '/data/',
    dataType: 'text',
    success: function(response) {
        this.setState({data: response})
        ReactDOM.render(<FilterTable rows = {response} />,document.getElementById('filterTableContainer'));
    }.bind(this)
});
}    
render() {
let {rows} = this.state.data
return (
        <div>
            WOW
            {this.state.data}
            <div id="filterTableContainer"></div>
        </div>
    );
}
like image 36
bhattshru Avatar answered Feb 15 '26 02:02

bhattshru



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!