I'm trying to pull data from a database using a javascript/jquery function to populate existing fields on a website before the initial render. My understanding is that I have to call ComponentWillMount in order to have the state ready before the initial render. Below is a sample of what I have
componentWillMount:function()
{
var currentPage = location.hash;
getform(globalObj["#login"]["sessionId"], globalObj["#encsearch"]["ID"], formType, function(err, data)
{
console.log("Start form")
var info = data["FormData"];
console.log("End form");
});
console.log("Start Outside")
this.setState({"fieldValuePairs": info});
console.log(this.state.fieldValuePairs);
console.log("End Outside")
}
},
render: function() {
console.log("Rendered first before FormData");
return(
<div className="twelve columns">
<PageBuilder handleChange={this.handleChange}
pageName= {this.props.currentPage}
layoutConfig={this.state.layout}
initDataObj={this.state.fieldValuePairs}
rowClasses="row"/>
</div>
);
}
});
function getForm(sessionId, ID, formType, done) {
$.getJSON('/api/los/loans/loan/forms/get_form/', {"sessionId": sessionId, "Id": ID, "formType": formType})
.done(function(data) {
done(null, data);
}).fail(function(err) {
done(err, null);
}).always(function() {
;
});
}
I saw this question and answer that is similar to what I am asking, React fetch data in server before render ,but the major difference is that I am calling and waiting for the data from a database to get back to me. Since Javascript does not wait for the data to come back, the initial render happens before the data is retrieved and the state is updated. I'm also unable to call this.state.fieldValuePairs inside the getform area; I assume it is because it is not in the scope of the function. Below is the execution order of the console log.
Start Outside
End Outside
Render first before FormData
Start Form
End Form
Question: How can I get the data before the initial render? Is it because the function is taking too much time in execution before var info = data["FormData"];?