Reputation: 113
I'm trying to query a URL string and pull in some weather data. I'm getting the response but for some reason, I'm not able to pull in the data. I'm getting an error saying cur
const weatherForm = document.querySelector("#weather-form");
weatherForm.addEventListener("submit", fetchWeather);
function fetchWeather(e) {
e.preventDefault();
const searchTerm = document.querySelector(".search").value;
fetch(`https://api.apixu.com/v1/current.json?key=c54944da22b147b48ec152033160205&q=${searchTerm}`)
.then((response) => {return response.json(); })
.then((resp => {
// console.log(resp);
let currentArray = resp.current;
console.log(currentArray);
showWeather(currentArray);
}))
.catch(err => console.log(err));
}
function showWeather(currentArray) {
alert("Hello");
const results = document.querySelector(".results");
let output = '<div class="container">';
currentArray.forEach((weatherData => {
output += `
<h2>${weatherData.feelslike_f}</h2>
`;
}))
document.querySelector(".results").innerHTML = output;
}
<form id="weather-form">
<input type="text" class="search">
<input type="submit" value="submit">
</form>
<div class="results"></div>
rentArray.forEach is not a function. Here is my code:
I think it has something to do with the way I'm doing let currentArray = resp.current
but I'm not sure. Any help would be greatly appreciated. Here is a link to my codepen if you would like to take a better look.
https://codepen.io/Brushel/pen/JBGGYp?editors=1011
Upvotes: 1
Views: 889
Reputation: 371049
The API is only returning a single object, not an array of objects. Fix showWeather
so that it only accesses the property of the object, rather than try to iterate over an array:
const weatherForm = document.querySelector("#weather-form");
weatherForm.addEventListener("submit", fetchWeather);
function fetchWeather(e) {
e.preventDefault();
const searchTerm = document.querySelector(".search").value;
fetch(`https://api.apixu.com/v1/current.json?key=c54944da22b147b48ec152033160205&q=${searchTerm}`)
.then((response) => {return response.json(); })
.then((resp => {
// console.log(resp);
let currentArray = resp.current;
// console.log(currentArray);
showWeather(currentArray);
}))
.catch(err => console.log(err));
}
function showWeather(weatherData) {
document.querySelector(".results").innerHTML = `
<div class="container">
<h2>${weatherData.feelslike_f}</h2>
</div>
`;
}
<form id="weather-form">
<input type="text" class="search">
<input type="submit" value="submit">
</form>
<div class="results"></div>
Upvotes: 2