Axios failing to retrieve nested data in get request

Having an issue with getting a 2d array using axios in my code. When I try to console.log it, it returns empty. Any suggestions?

Here's the piece of code causing trouble:

let orig = []
      axios
        .get(<endpoint url here>)
        .then(response => {
          orig = response.data.activity_history
        })

      console.log('Orig -> ' + JSON.stringify(orig))

The endpoint is designed to return data structured like this:

{
    "id": 1,
    ...
    "activity_history": [
        [
            "Test",
            "Test",
            "Test",
            "Test",
            "Test"
        ]
    ]
}

I need to access the 2d array so that I can add another array to it on the frontend. However, the console log for orig displays as Orig -> []. Any ideas on how to resolve this?

Answer №1

due to the asynchronous nature of axios calls, the console.log statement does not wait for the call to finish. One solution is to use the await keyword with axios. Another approach is to handle all actions involving Orig within the then function as shown below:

  axios
        .get(<endpoint url here>)
        .then(response => {
          orig = response.data.activity_history;
          console.log('Orig -> ' + JSON.stringify(orig))
        })

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

Top way to include an HTML and javascript file in an Ext.Panel within Sencha Touch

My main goal is to efficiently include external HTML files and display them on an Ext.Panel in Sencha touch 2.3 by creating a wrapper module for the HTML file that can be instantiated using xtype, with an external Javascript file for event handling. Updat ...

What is the best way to send information from App.js to components?

In my project, I am working with App.js and a functional component called "uploadlist". The goal is to pass a 'custid' value from App.js to the uploadlist component. Here's what I have attempted: app.js: export default class App extends Com ...

Ways to reach the Document Object Model in a functional component

While working on a speedometer project in ReactJS with some vanilla syntax, I encountered an issue where the canvas element was returning null. Oddly enough, when running const canvas = document.getElementById('dial__container'); in the console, ...

Trying out RestfulController functionality in Grails

Currently, I am in the process of writing integration tests for a RestfulController within Grails 2.4.0 that responds in JSON format. The index()-Method within the controller is implemented as shown below: class PersonController extends RestfulController& ...

The Forge Viewer's getState() function is providing inaccurate values for individual items

In our Angular application, we have integrated the latest version of Forge Viewer and are storing the current state of the viewer in our database for future restoration. After thorough testing, we discovered that isolated nodes are not being saved correct ...

Changing multiple PHP variables into a JSON object

My PHP script has multiple variables: $name = "John"; $age = 30; $city = "New York"; // and more... Is there a way to combine these variables into a single JSON object? Can this be achieved in PHP? ...

Sharing a state object with another React file can be accomplished by using props or context to

My first React file makes an API call to retrieve data and save it in the state as Data. import React, { Component } from "react"; import axios from "axios"; import Layout from "./Layout"; class Db extends Component { constructor() { super(); th ...

Changing a list into a specific JSON format using Python

I've encountered an issue where my output looks like this: List containing a long string ["21:15-21:30 IllegalAgrumentsException 1, 21:15-21:30 NullPointerException 2, 22:00-22:15 UserNotFoundException 1, 22:15-22:30 NullPointerException 1 ...

An elusive melody that plays only when I execute the play command

I am currently working on creating a music Discord bot using the yt-search library, however, I am encountering an issue where it returns undefined when trying to play a song and joins the voice channel without actually playing anything. My approach is to u ...

The absence of multiple lines on the x-axis in the linear chart was noticeable

Currently, I am facing an issue with loading a single axis line chart on my Dashboard.vue. The functionality involves users selecting a 'year' and a 'loan_type' from dropdown menus, after which the chart should display a 12-month record ...

Utilizing a particular Google font site-wide in a Next.js project, restricted to only the default route

My goal is to implement the 'Roboto' font globally in my Next.js project. Below is my main layout file where I attempted to do so following the documentation provided. import type { Metadata } from "next"; import { Roboto } from "n ...

The React popup window refuses to close on mobile devices

I am currently facing an issue with a site (a react app) deployed on GitHub pages. The site features cards that, when clicked on, should open a modal/dialog box. Ideally, clicking on the modal should close it. However, I have encountered a problem specific ...

What is the process for extracting information from couchdb and transferring it into a pandas dataframe?

After downloading Twitter data onto my local couchdb server in JSON files, I am trying to access the database using Python. First, I import the necessary libraries: import couchdb import pandas as pd from couchdbkit import Server import json import cloud ...

`The ng-binding directive seems to be malfunctioning while ng-model is functioning properly

Currently, I am in the process of learning how to utilize Angular (1.3.10). My objective is to create two input fields that will specify the suit and value for a hand of playing cards. In my attempts to achieve this, I have encountered an issue. When I man ...

Determine in Node.js whether a variable is present in the request object for each page the user visits

Currently, my authentication system utilizes passportjs to define req.user when the user is logged in. As my website expands beyond its current 5 pages, I have been checking for the existence of req.user at the top of each route. Based on whether it exist ...

What is the process for transmitting data in JSON format generated by Python to JavaScript?

Utilizing Python libraries cherrypy and Jinja, my web pages are being served by two Python files: Main.py (responsible for handling web pages) and search.py (containing server-side functions). I have implemented a dynamic dropdown list using JavaScript w ...

When attempting to parse JSON in Python, I encounter the error message: 'TypeError: list indices must be integers or slices, not str'

After making a request using the requests library, I receive the following JSON response: { "tracks":[ { "bframes":0, "bitrate":155, "codec":"h264", "content":& ...

Having trouble invoking an express route on mobile devices using the .click method

I'm experiencing a strange issue where my code works perfectly in Chrome browser but fails to function on my phone. Here's the snippet of code causing the problem: $('#plusSign').on('click', function() { var myLin ...

Guide on how to fill a jQuery DataTable with data from an XMLHttpRequest response

I have come across multiple inquiries on this topic, but none of the solutions provided have brought me close enough to resolving my issue. Hopefully, someone out there will find it simple to address. I am attempting to populate a DataTable using an XHR re ...

ERROR UnhandledTypeError: Unable to access attributes of null (attempting to retrieve 'pipe')

When I include "{ observe: 'response' }" in my request, why do I encounter an error (ERROR TypeError: Cannot read properties of undefined (reading 'pipe'))? This is to retrieve all headers. let answer = this.http.post<ResponseLog ...