Error: Axios data stored in an array is returning as undefined

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

Answer №1

axios.get is an asynchronous function that occurs at a later time, while your custom function is synchronous. This means that getWeatherData() executes immediately without waiting for the results of axios.get.

To address this issue, you can utilize promises or callbacks based on your preference. A promise-based solution would be structured 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)
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Separate arrays containing latitude and longitude coordinates to map out all potential points of (latitude, longitude)

I need to identify all potential points created by latitude and longitude coordinates stored in separate arrays: a = np.array([71,75]) b = np.array([43,42]) Is there a simple method to achieve this without generating redundant pairs? I've experimen ...

Upon upgrading to Angular 8, the function this._delegate.setNgStyle is not recognized

Following the update of my project from Angular 7 to Angular 8 and resolving all errors caused by breaking changes, I am encountering a new issue: <div fxFill ngStyle.xs="overflow:auto"> This line is resulting in the following error: ERROR Type ...

What is the recommended format for storing timestamps in JSON when performing MongoDB queries with Node.js?

Currently, my data preprocessing in Python involves converting it into JSON and then inserting it into a collection using Node.js like this: collection.insert(data, {safe:true}, function(err, result) {}); Along with that, I will be executing queries using ...

Tips for extracting JSON components from an HTTP response string using Python

I am currently learning how to parse JSON data from an HTTP API in Python. Below is the code I have written to parse the HTTP content as a string and extract a JSON object array: import json from urllib.request import urlopen apilink = urlopen("api link" ...

Developing a dynamic modal using Angular and embedding Google Maps within an iframe

I'm currently working on implementing a modal in my Angular application that, when opened, displays Google Maps within an iframe. The problem I'm facing is that the iframe isn't loading and I'm receiving this error in the browser conso ...

Generate fresh columns from string columns formatted as JSON

I have a table with a single column that is of string type, but the content resembles a JSON structure. The data in the column looks like this: 'old_id' column with values: [{"name":"Entitas Penugasan","id":"6415","value":"HIJRA"}, {"name":"Fu ...

Filter out any items from the JSON data that include a designated keyword

Can anyone suggest the most efficient way to filter out objects from JSON data that contain a specific term or keyword? Here's an example of my JSON data: json = [{ "name":"John", "age":30, "cars":"BMW" }, { "name":"Micheal", "age":30, "cars": ...

What are the best strategies for protecting a JSON file using REST API or alternative approaches?

I've been searching everywhere for information that I find difficult to understand. I am currently using a WAMP server and have successfully executed a "SELECT name FROM Tablename" query, passing the data to json_encode(). I am pleased with the result ...

Tips for styling a mat-checkbox correctly

I'm working on customizing the appearance of a mat-checkbox (material2) to meet the following specifications: Always display a black border (#000000), regardless of whether the checkbox is checked or not When the checkbox is checked, show a white ti ...

Generating a compilation of indices containing elements with '1' and '-1' from a two-dimensional numpy array

I've been working on a 2D numpy array, randomly inserting '1's and '-1's over multiple iterations. Now, I'm looking to retrieve the list of indices where these values are located. Here's an excerpt from my code: import m ...

Is it best to make a refactored/service method public or private in Typescript?

Objective: I need to refactor a method in my component that is used across multiple components, and move it to a service class for better organization. Context: The method in question takes a user's date of birth input from a profile form and convert ...

Investigate similarities between two numpy arrays in Python to identify clusters and eliminate redundancies

Consider the following two arrays: x = np.array([1,2,2,3,4,1,2,4,3,3]) y = np.array([100,200,200,100,400,100,200,400,100,100]) In array x, we observe that there are two occurrences of 1 and corresponding to those same positions, we find two instances of 1 ...

I cannot seem to locate the System.Json.DLL file

I've been testing out some JSON examples with the Http Client, but they mention a System.Json.DLL that I can't seem to locate. Check out this resource for more information on System.Json.DLL, but it's not showing up in my installed files. Co ...

Tips for transforming JSONTokener into JSONArray and JSONObject on an android device

Trying to convert a JSONTokener to JSONArray and JSONObject seems to be causing issues for me. I've searched online for solutions, but the sample codes haven't been working for me. Can anyone spot what's going wrong? StringBuilder builder= ...

What is the best way to change an array element into a string in TypeScript?

Within my Angular 2 component, I am utilizing an array named fieldlist which is populated by data retrieved from an http.get request. The array is declared as follows: fieldlist: string[] = []; I populate this array by iterating through the JSON response ...

What is the best way to save all of the links into a CSV or text file?

import urllib.request as req import re import bs4 import csv url="https://en.wikipedia.org/wiki/South_China_Morning_Post" request=req.Request(url,headers={ "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/5 ...

What is the necessity of requiring a parameter with the type "any"?

There is a function in my code that takes a single parameter of type any: function doSomething(param: any) { // Code to handle the param } When I call this function without passing any arguments: doSomething(); An error is thrown saying: "Expected 1 ...

Despite setting the esModuleInterop flag, I am still encountering an error with default imports

My React project with TypeScript is causing some issues. In the main tsx file, the import React from 'react' line works fine. However, in my test file, I keep getting the TS1259 error. I suspect there might be a problem with my TS/Jest/Babel conf ...

The first element in the array data is not present in the struct returned from the C++ DLL

In my Unity5 program, I am using a shared structure (smMsg) to transmit data from a C++ DLL to C#. The structure includes an array: [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)] public float[] mtx; This array represents a 4x4 Matrix, hence the f ...

Tips for swapping out the data array in my ChartJS graph

I am currently working on a project that involves changing the data array of a chart with a completely different one. Unfortunately, although my code is successfully updating the labels of the chart, the data itself remains unchanged and I cannot figure ou ...