I'm trying to make a call to the Trip Advisor API and return some data using an async/await function.
The async/await function is defined in a file named req.js and the code is below:
const findRest = async (reviews, closed) => {
const respond = await fetch(
https://tripadvisor1.p.rapidapi.com/restaurants/list-by-latlng?limit=30¤cy=EUR&distance=2&lunit=km&lang=en_US&latitude=53.3498&longitude=-6.2603,
{
method: GET,
headers: {
x-rapidapi-host: tripadvisor1.p.rapidapi.com,
x-rapidapi-key: x-rapidapi-key
}
}
);
if (respond.status === 200) {
let data = await respond.json();
let newData = await data.data;
let data1 = await newData.filter(
review => parseInt(review.num_reviews) >= reviews
);
let data2 = await data1.filter(close => close.is_closed == closed);
return data2;
} else {
throw new Error(Could not provide results within specified parameters);
}
};
This is then called when an event listener fires by clicking a button in a small form. This code is in a file named app.js and is below:
document.getElementById(subButton).addEventListener(click, function(e) {
const userReviews = parseInt(document.querySelector(.userRev).value);
const userClose = document.querySelector(.userClose).value;
e.preventDefault();
console.log(click);
console.log(e.target.id);
findRest(userReviews, userClose)
.then(data =>
data.forEach(element =>
console.log(
`${element.name} matches your search criterea and is located at ${element.address}
To make a booking, please call ${element.phone}`
)
)
)
.catch(err => console.log(err));
});
And for reference here is the HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset=UTF-8 />
<meta name=viewport content=width=device-width,initial-scale=1 />
<title>API Tester</title>
<meta name=author content=Phil My Glass />
<meta
name=description
content=An app to help me practice my API calling
/>
</head>
<body>
<header>
<h1>What Restaurant?</h1>
</header>
<main>
<form id=form>
<input id=userRev class=userRev /><br />
<input id=userClose class=userClose />
<button id=subButton class=subButton type=submit>Find!</button>
</form>
</main>
</body>
<script src=req.js type=text/Javascript></script>
<script src=app.js type=text/Javascript></script>
</html>
When I run the findRest function within the app.js file, but outside the event listener and pass in the arguments as static data it executes just find and prints all the requested data to the console. As soon as I try and run it within the event listener nothing happens. No returned data printing, no error and it's killing me why.
Like I said, it works fine outside the event listener, but I've tried changing the forEach to map and still nothing is being returned. Can someone please help!