Simplified:
Retrieve data using Axios
Store the data in an array and return the array at the end of the function
The array is then passed to another function
Print the data from the array using console.log
Why does it show as undefined?
Long Story:
I am restructuring my code to adhere to the Single Responsibility Principle, thus, the function now handles the retrieval and return of weather data. In the future, I plan to create a single function that will incorporate these elements into the HTML DOM.
I need to extract specific variables from the API's response, As I'm still grasping JSON basics, I simplified the results for clarity. Considering that I'm working with Typescript, there might be a typing mishap causing this issue. Even after going through the documentation, I couldn't find the solution—I'm left with only seeking help here.
export function getWeatherData(api : string) {
var weatherData: any = []
axios.get(api)
.then(function (response) {
weatherData.push(response.data.city.name)
})
.catch(function(error){
console.log(error)
})
return weatherData
}
enter image description here console.log(weatherData)
function main() {
var city = getCity()
var api = getApi(city)
let weatherData = getWeatherData(api)
console.log(weatherData)
clearDivs()
addDivs(howManyReadings)
addDataToDivs(weatherData)
}
export function addDataToDivs(weatherData: any) {
// let li = document.getElementsByClassName("weatherInnerContainer")
// let nI = li.length
// for (var i = 0; i < nI; i++) {
console.log(weatherData[0])
// li[i].appendChild(weatherData['city']['name'])
// li[i].appendChild(weatherData['list'][i.toString()]['main']['temp'])
// li[i].appendChild(weatherData['list'][i.toString()]['dt_txt'])
// li[i].appendChild(weatherData['list'][i.toString()]['weather']['0']['description'])
// let nElement = document.createElement('img')
// let iconValue = (weatherData['list'][i.toString()]['weather']['0']['icon']).toString()
// let iconLink = 'https://openweathermap.org/img/wn/' + iconValue + '@2x.png'
// nElement.src = iconLink
// li[i].appendChild(nElement)
// }
}
Console returns: undefined