0

Simplified:

Use Axios to get data

Place data in an array and end function with return array

The array is passed to function

console log data from the array

why is it returning undefined?


Long Story:

I am re-coding to the Single responsibility principle, so the function calls and returns weather data, Later on, create a single function that adds data as elements to the hmtlDom.

I need to be able to select specific variables from the API data, I'm just learning JSON and I was sure I was doing it wrong, so I simplified the results, I'm working in Typescript, so it might be a typing issue. reading through documentation hasn't helped, Last Resort is 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

1 Answers1

0

axios.get is asynchronous function, which happens 'at a some time', while the function you made is synchronous. This means, that execution of getWeatherData() is immediate, and it does not wait for the results of axios.get.

You can solve this by using promises or callbacks, whichever you prefer. Promise based solution would look something like this:

export function getWeatherData(api : string) {
    return axios.get(api)
        .then(function (response) {
            return response.data.city.name
        })
        .catch(function(error){
           console.log(error)
        })
}


function main() {
  var city = getCity()
  var api = getApi(city)
  getWeatherData(api).then(weatherData => {
     console.log(weatherData)
     clearDivs()
     addDivs(howManyReadings)
     addDataToDivs(weatherData)
  }
}

user3133
  • 592
  • 4
  • 12