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.
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>
);
}
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>
);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With