I have a reactJS application where I am trying to validate some user input against a database value. The database is stored on AWS so I am using a fetch to a Web API that I wrote. This is the code that I am executing:
passString = "003" + newValue;
console.log("call function with ", passString);
var returnedValue = mqRequest(passString);
console.log("return from fetch with ", returnedValue);
if (returnedValue != newValue) {
localPlanID.message = "The Plan ID you entered was not found on our system";
localPlanID.css = "textbox4Bytes input-box-error";
}
The value of the variable newValue is VSTA
The code will call a function called mqRequest that is in a separate file. I include this by using this line of code:
import {mqRequest} from '../functions/commonFunctions.js';
The code of the function looks like this:
export function mqRequest (passedData) {
//var url = "https://webaccuapi-dev.accurecord-direct.com/api/homepage?mqRequest=" + passedData;
var url = "http://webaccuapi-dev.accurecord-direct.com/api/homepage?mqRequest=" + passedData;
const options = { method: 'GET' };
var returnString = "";
fetch(url, options)
.then(function(response) {
return response.json();
})
.then(function(myJson) {
if (myJson == undefined)
{
returnString = "fetch failed";
}
else
{
returnString = myJson[0].return_response;
console.log("from function, myJson[0] = ", myJson[0]);
}
});
console.log("from function, after fetch, returnString = ", returnString);
return returnString;
}
When I execute the code, this is what I see in the console.log:
call function with 003VSTA
from function, after fetch, returnString =
return from fetch with
from function, myJson[0] = {return_response: "VSTA", return_code: "0", return_plan_name: "N/A", return_menu_string: "N/A"}
So, it appears that I am calling the function and passing it 003VSTA. The function picks up this value, builds the url variable, and executes the fetch. The fetch returns myJson[0].return_response with a value of VSTA which is correct!
The problem that I am having is, I think, a timing issue. I believe the function is called but the code is continuing to execute even though the function and fetch have not finished executing. How do I get the code to wait for a value to be returned by the function before continuing?
Thanks.