It seems like I've overcomplicated this problem for myself. In my page, I have 2 XMLHTTPRequests - the first request retrieves data from an API and fills my elements with this data. However, one of the fields in my elements requires a second request to a different endpoint using a value received from the first request, but it always ends up being filled with undefined.
I understand that this is happening because of the asynchronous nature of the request, where the site continues loading without waiting for the request to complete. I tried making the second request synchronous, but the issue persists (now causing the site to freeze briefly). I also attempted to use async/await, but my text editor gave me an error saying "await has no effect on the type of this expression," and now I'm at a standstill.
I believe my struggle stems from a lack of experience and understanding of asynchronous JavaScript (this is my first application using it).
Below is the code snippet:
let ourGrid = document.getElementById("res");
let searchValue;
function search() {
searchValue = document.getElementById("search").value;
getFoods(`https://api.spoonacular.com/recipes/findByIngredients?ingredients=${searchValue}&number=2&apiKey=${apikey}`);
}
function getFoods(url) {
let xhr = new XMLHttpRequest();
xhr.responseType = 'json';
xhr.onreadystatechange = () => {
if(xhr.readyState == XMLHttpRequest.DONE) {
setFoods(xhr.response);
} else {
return "error";
}
};
xhr.open('GET', url);
xhr.send();
}
function setFoods(json) {
if(json.length == 0) {
alert(`No results found for ${searchValue}`);
}else{
ourGrid.innerHTML = json.map(foodLogic).join("");
}
}
function foodLogic(foodItem) {
return `<div class="imageItem"><img src="${foodItem.image}"></div>
<div class="infoItem"><h2>${foodItem.title}</h2>
<p class="summary">${requestSummary(foodItem.id)}</p>
<p class="more"><a href="./moreInfo.html" target="_blank">More</a></p></div>`;
}
function requestSummary(id) {
let url2 = `https://api.spoonacular.com/recipes/${id}/summary?apiKey=${apikey}`;
let xhr2 = new XMLHttpRequest();
xhr2.onreadystatechange = () => {
if(xhr2.readyState == XMLHttpRequest.DONE){
return returnSummary(JSON.stringify(xhr2.response));
}
};
xhr2.open('GET', url2, false);
xhr2.send();
}
function returnSummary(json) {
return json.summary;
}