Guide on retrieving data from an axios promise in JavaScript

I am struggling to manage the output of multiple lists retrieved through an axios API call made in JavaScript. I want to know how to effectively log the results and save them for future use, particularly for creating a data visualization.

Here is my current code:

const axios = require('axios');

var years = []
var totals = []
var rail = []
var bus = []
var para = []


const getTotal = async () => {
    const url="https://data.cityofchicago.org/resource/w8km-9pzd.json";

    var totals = []
    try {
        let res = await axios.get(url);

        for (i = 0; i < res.data.length; i++) {
            totals.push(res.data[i].total);
            years.push(res.data[i].year);
            rail.push(res.data[i].rail);
            bus.push(res.data[i].bus);
            para.push(res.data[i].para);
        }

    }catch(error) {
        console.log(error);
      }
      return(totals,years,rail,bus,para) 
}

//data = axiosDataFetch().bus;
console.log(getTotal())

How can I display the contents of the 'totals' list here instead of it showing as undefined? I have made some changes based on feedback received, with the goal being able to access and utilize the five lists obtained from the API for data visualization purposes.

Answer №1

Make sure to include the await keyword before calling axios, then work with the response object (res) instead of using the .then method.

const axios = require('axios');

async function fetchAxiosData() {
    const url="https://data.cityofchicago.org/resource/w8km-9pzd.json";

    var totals = []
    let res = await axios.get(url);

    for (i = 0; i < res.data.length; i++) {
        totals += res.data[i].total;
    }

    console.log(res.result) 
}

fetchAxiosData();

Javascript inherently operates in an asynchronous manner (e.g. the timing of the axios call's completion is uncertain, so it may not sync with your program).

To understand different methods of handling asynchronous behavior, check out this detailed article. Although lengthy, grasping its concepts will save you valuable time in the future.

Answer №2

Make sure to log the totals from inside your then function. The issue is likely that your current log statement is being executed before axios finishes fetching the data.

const axios = require('axios');
const url="https://data.cityofchicago.org/resource/w8km-9pzd.json";

var totals = []
let res = axios.get(url)
    .then(result=>function(response){
        for (i = 0; i < response.data.length; i++) {

            totals += response.data[i].total;

          }
         console.log(totals); // include this line inside the 'then' block
    }
    )
    .catch(function (error) {
      console.log(error)
    });   

Answer №3

    const axios = require('axios');
    const url="https://data.cityofchicago.org/resource/w8km-9pzd.json";

    const fetchData = async () => {
      var dataTotals = []
      try {
        let response = await axios.get(url);
        for (i = 0; i < response.data.length; i++) {
            dataTotals.push(response.data[i].total);
        }
        console.log(dataTotals);
      } catch(error) {
        console.log(error);
      }
      return dataTotals;
    }

Apologies for the confusion, I didn't realize that you needed to run the query at the top level, resulting in the pending response due to getTotals function returning a promise. To resolve this issue, use the following code:

fetchData().then(result => {
  console.log(result);
});

This is not a common occurrence as we usually have our code modularized, which means when imported, it is encapsulated within an IIFE.

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

Error: Attempting to append a child to a non-existent property

I am currently learning Java Script and this is the code I have been working on. <!doctype html> <html> <head> <style> div {position:absolute; width:500px; height:500px} img {position:absolute} ...

Invalid for the purpose of storage

Encountering the following error message: The dollar ($) prefixed field '$size' in 'analytics.visits.amounts..$size' is not valid for storage. return Manager.updateMany({}, { $push: { & ...

The 8 x 8 grid I am constructing is functional, however, the issue lies in the fact that the first line only begins with a single # symbol

I am attempting to create an 8 x 8 grid. It's coming together, but the issue is that the first line only starts with one # sign. function print(msg) { console.log(msg); return msg; } let result = ""; for(let i=1; i<=8; i++) { result += ...

Combining ReactJS event handling for onClick and onKeyDown into a single handler for TypeScript

To ensure accessibility compliance, I am incorporating onKeyPress handlers into my application. However, I am facing a challenge with interactive <div /> elements. Here are the event handlers I want to trigger on click: const handleViewInfoClick = ( ...

Having trouble making md-data-table directives function properly

I'm struggling to incorporate the md-data-table library from https://github.com/daniel-nagy/md-data-table into my webpage. Despite loading the library in Chrome, none of the directives seem to be working. Here's a snippet of my code - can anyone ...

What steps are involved in enabling Server Side Rendering with Next.js?

For my exploration of Next.js, I started by setting up a new Next.js project and incorporating code to retrieve weather data: export default function Home() { const [data, setData] = useState(null); useEffect(() => { fetch("https://api.we ...

Is there a method to incorporate a click event for the confirm button in the ElMessageBox UI element?

When I try to remove data from the table, I need a warning message to appear in the center of the screen first. The delete function is already set up, but I'm struggling to figure out how to implement a confirm button click event with ElMessageBox. I ...

What strategies can be implemented to decrease the value of the writing box by 2.5%?

I would like to decrease the value in the input box by 2.5%. Here is the HTML code snippet: <div class="ZakatCalc"> <div class="calcimg"> <img src="" alt="" srcset="" class=" ...

I'm encountering an issue with my React 18 application using TypeScript: the module './App' cannot be found

Encountering an issue while attempting to update to react 18. I'm curious if this problem is related to my file types. I am using Typescript, so do both the app and index files need to have a .tsx extension? Both the app and index files are located ...

Error encountered in Intellij for Typescript interface: SyntaxError - Unexpected identifier

I am currently testing a basic interface with the following code: interface TestInterface { id: number; text: string; } const testInterfaceImplementation: TestInterface = { id: 1, text: 'sample text' }; console.log(testInterface ...

"Explore the versatility of React Day Picker with customizable months and weekdays_long

I have implemented the following packages: "react": "^18.2.0", "react-day-picker": "^8.1.0", and I am attempting to translate the months and days into French. However, despite passing the translated arrays to my < ...

Discover the best practices for utilizing CSS selectors reliably in puppeteer

For a project, I am currently working on customizing a puppeteer script that is able to play a song from Soundcloud and record it. The main goal is to utilize a CSS selector to display the duration of the song as well. I am encountering difficulties with g ...

Launching a web application directly from a USB drive

Exploring the world of Javascript frameworks and nodejs, I recently encountered a unique requirement that got me thinking about their practical application. The requirements are as follows: --I need to create a lightweight website that can be run from a U ...

Enhanced Fancybox Version 2 adjusts iframe width to fit content

I have been attempting to adjust the width of the iframe in fancybox v2 to fit my content properly. However, every time I try, the content appears too large within the iframe and requires horizontal scrolling to view it all. My goal is to see the entire wi ...

PHP Header Redirect Not Redirecting Correctly

As a newcomer to PHP, I conducted some research and attempted to implement a solution found on Stack Overflow, but unfortunately, it did not work for me. My goal is to redirect users to another page after a specific code has been executed. Despite removing ...

Response coming from an ajax call in the form of a JSON

With the JSON string provided below: {cols:[{"id":"t","label":"Title","type":"string"},{"id":"l","label":"Avg ","type":"string"},{"id":"lb","label":"High","type":"string"},{"id":"lo","label":"Low","type":"string"}],rows:[{"c":[{"v":"Change navigation"},{"v ...

Guide on populating a textbox with values through Ajax or Jquery

Consider the scenario where there are three textboxes. The first textbox requires an ID or number (which serves as the primary key in a table). Upon entering the ID, the semester and branch fields should be automatically filled using that ID. All three fie ...

Incorporating jquery-ui Datepicker with dynamic text input functionality

In my table list, I have multiple input fields with the jQuery datepicker implemented. Each input field is assigned the class "datepicker" and a unique ID number. When clicked on, the datepicker pops up allowing for date selection to be inserted into the f ...

The onload function in jQuery is not functioning properly when the page is refreshed

I'm just starting out with jquery and I have a simple project in mind. The idea is to have two pictures stacked on top of each other, but I want the page to start showing the second picture first (at a specific scroll point). Then as the user scrolls ...

Closing the React Material UI drawer with nested list items upon clickingORClicking on nested list

Currently, I am encountering an issue with my React project that utilizes Material-UI. The problem arises when I incorporate nested list items within the drawer component. Previously, everything was functioning smoothly until the addition of these nested i ...