I'm doing an AJAX query to assign the value to a variable that has to be declared in another function (I'm using React). I have the following code:
In a function A:
var datos = getAllProfessionals();
In getAllProfessionals():
function getAllProfessionals() {
var jsonResponse;
$.ajax({
type: 'GET',
url: urlAjaxGetAllProfessionals, // Defined at HTML file
async: false
}).done(function(response) {
jsonResponse = response;
});
return jsonResponse;
},
I was forced to put Async: false
because without that data there is nothing to display on the page, and also if or if it has to be stored in data. but i can't do
...
}).done(function(response) {
return response;
});
And if I leave the variable out of the $.ajax() function the value is lost because it's asynchronous.
What alternatives do I have to avoid putting the async: false
and receive the answer without problems?
You must keep in mind that React components work as state machines, the Data of a React component always comes from either the state or the props (properties), when you mutate the state or the props the React component automatically reacts to these changes and re-renders doing the necessary calculations to modify the view by making as few changes to the DOM as possible. your solution breaks this whole concept and you are not using React for what it was created for since you are not mutating the state depending on the response from the server and you are not using the React component to do the updates in the view.
Take a look at the following implementation (ES6)
The ajax request is made at the moment of mounting the component, the component decides what content to render depending on the state, you only mutate the state and the view will react accordingly.
What you can do is call a function when the information has been received (callback function). To do this you can put the attribute
success
with the name of the function to which you want to pass the data in your ajax call and when the information has been received it will call that function passing the information that has been received as parameters.It would be something like this: