I am currently facing an issue while integrating the OpenWeatherMap API into my web application. I have carefully implemented the code to fetch weather data based on user input, but I am encountering the following error in the console:
Uncaught (in promise) TypeError: locations is not iterable searchTimeout app.js:55 fetchData api.js:14
I have provided the relevant code snippet below for your reference:
app.js:
"use strict";
import { fetchData, url } from "./api.js";
import * as module from "./module.js";
// Code for toggleSearch, addEventOnElements, and other functions is here...
const searchField = document.querySelector("[data-search-field]");
const searchResult = document.querySelector("[data-search-result]");
let searchTimeout = null;
const searchTimeoutDuration = 500;
searchField.addEventListener("input", function () {
searchTimeout ?? clearTimeout(searchTimeout);
if (!searchField.value) {
searchResult.classList.remove("active");
searchResult.innerHTML = "";
searchField.classList.remove("searching");
} else {
searchField.classList.add("searching");
}
if (searchField.value) {
searchTimeout = setTimeout(() => {
fetchData(url.geo(searchField.value), function (locations) {
// Code to handle fetched data and display results is here...
});
}, searchTimeoutDuration);
}
});
api.js:
/**
* Fetch Data from Server
*@param {String} URL API url
*@param {Function} callback callback
*/
export const fetchData = function (URL, callback) {
fetch(`${URL}&appid=${api_key}`)
.then((res) => res.json())
.then((data) => callback(data));
};
export const url = {
// API URL construction methods...
};
I suspect that the issue might be related to the format of the data returned from the API call or how it is being handled within the fetchData function. However, I have verified the API key and ensured that the fetchData function works as expected for other API endpoints in the application.
I kindly request your assistance in resolving this issue. I would greatly appreciate any insights or suggestions you may have to identify and fix the root cause of this error. Additionally, if there are any improvements I can make to the code structure or API integration approach, please feel free to share your expertise.
If you require any further information or additional code snippets, please let me know, and I will be more than happy to provide them.