Class component proceeding without waiting for function completion

My function, getactivity(), pulls and sorts data from an API and returns the sorted data in answer1 format. However, I am facing a problem where whenever I run the function to retrieve the data, it keeps returning nothing.

Here is the full code:

import React, { Component, Fragment } from 'react';
import axios from 'axios';
import Pusher from 'pusher-js';
import Stats from '../../components/Stats';
import Layout from '../../components/Layout';

const choices = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'];

let curr = new Date 
let week = []

for (let i = 1; i <= 7; i++) {
  let first = curr.getDate() - curr.getDay() + i 
  let day = new Date(curr.setDate(first)).toISOString().slice(0, 10)
  week.push(day)
}

// console.log(week)

function getactivity() {

    axios.get('/api/profiles/stats')
      .then(response => {
        const activity = response.data["Drinks"]

        var o = {};
        activity.forEach((i) => {
          var Date = i.Date;
          i.count = parseInt(i.count)
          if (!o[Date]) {
            return o[Date] = i
          }
          return o[Date].count = o[Date].count + i.count
        })

        var res = []
        Object.keys(o).forEach((key) => {
         res.push(o[key])
        })

        var answer1 = ""
        for (const x of res) {
            if(week.includes(x.Date)) {
                answer1 = answer1 + "[" + x.Date + "]" + ": " + x.count + ", "
            }
        }
        console.log("return: " + answer1)
        return answer1
    }, error => {
    console.log(error);
  });
}

console.log("act: " + getactivity())

class IndexPage extends Component {

    state = { answers: getactivity() }

  render() {

    return (
      <Layout pageTitle="AA Drinking activity">
        <main className="container-fluid position-absolute h-100 bg-light">
          <div className="row position-absolute w-100 h-100">
            <section className="col-md-5 position-relative d-flex flex-wrap h-100 align-items-start align-content-between bg-white px-0">
                <Stats choices={choices} stats={this.state.answers} />
            </section>

          </div>
        </main>
      </Layout>
    );
  }

};

export default () => (
    <Fragment>
        <IndexPage />
        <style global jsx>{`

            .custom-control-label {
                background: transparent;
                color: #999;
                font-size: 2rem;
                font-weight: 500;
                cursor: pointer;
                line-height: 2.25rem;
            }

            .custom-control-label:before, .custom-control-label:after {
                top: 0;
                left: -10px;
                height: 2.25rem;
                width: 2.25rem;
                cursor: pointer;
                box-shadow: none !important;
            }

            .custom-control-label.checked {
                color: #007bff !important;
            }

            button.btn {
                letter-spacing: 1px;
                font-size: 1rem;
                font-weight: 600;
            }

        `}</style>
    </Fragment>
);

The order of the console.log() does not appear as expected. It prints in this order:

act: undefined

return: [2020-12-08]: 10, [2020-12-09]: 7, [2020-12-10]: 4, [2020-12-11]: 3,

I assumed that the return should be printed first.

Answer №1

The reason for this error is that JavaScript runs asynchronously, meaning it doesn't wait for server responses (such as those from axios calls) before continuing its execution. One possible solution in your scenario would be to encapsulate the code you want to execute within a chained 'then' block like so:

axios.get('/api/profiles/stats')
  .then(response => {
    // Code executed immediately after axios call...
  }.then(activity=>{
    console.log("act: "+activity);
  });

If you need to utilize getActivity within a function, you can use async/await. For more information, you can refer to this useful link here.

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

retrieve information from a div using an AJAX request

I don't have much experience with ajax and javascript, but I need some assistance, so I will do my best to explain clearly! Below is the JavaScript associated with a button: $('#button-confirm').on('click', function() { $.ajax({ ...

Input form with multiple fields. Automatically display or hide labels based on whether each field is populated or empty

I am attempting to create a form where the placeholders move to the top of the input when it is focused or filled. However, I have encountered an issue with having multiple inputs on the same page. Currently, my JavaScript code affects all inputs on the pa ...

What is the best way to streamline the if statement in JavaScript?

Here is the given code snippet: public noArtistBeingEdited(): boolean { if (this.isFirstNameBeingEdited()) { return false; } if (this.isLastNameBeingEditable()) { return false; } return true; } What are some ways to ma ...

"Encountered an error: File or directory not found while attempting to export a function

src/test.js module.exports.test = function() { const { readFileSync } = require('fs'); console.log(readFileSync('test.txt', 'utf8').toString()) } index.js const { test } = require('./src/test.js'); test(); ...

Steps to Extract the key value from the parseJson() function

Could someone assist me in retrieving the value of the "id_user" key from the script provided below? JSON.parse({ "data": [ { "id_user": "351023", "name": "", "age": "29", "link": "http://domain. ...

Streamlining a complex task in JavaScript

I am currently exploring options to streamline my code so that I don't need to repeat the same function 38 times. Instead, I would like to have a single function that can handle 38 different IDs separately. The script is designed to randomly select a ...

Tips on how to correctly pass a .JSON object in the setState function of a reactJS

I am having an issue when attempting to pass a .json file in the following format: this is my class import MyForm from './MyForm'; class CreateProject extends React.Component{ constructor(){ super(); this.state = { categori ...

"Utilize Vue i18n to properly display currency amounts in USD

Whenever I present my currency as USD, it always shows up like this: USD$500.00. I am attempting to eliminate the USD prefix from the beginning. Below is my numberFormats configuration: numberFormats: { 'en': { currency: { ...

Building numerous pagination features in a single page using Codeigniter

I'm just starting out with codeigniter and I need help creating multiple paginations on one page. I've tried it, but only one pagination is working while the others are giving me errors. Can someone please assist me? I read some suggestions that ...

Node.js post request body is still showing as undefined despite using body-parser

Hello everyone, I am currently using Node.js to implement a Dialogflow chatbot. My goal is to extract parameters from an HTTP POST request. To achieve this, I utilized Postman and made sure to set the content type to JSON in the header. Below is the code f ...

updating the count of items in a react virtual list

Popular libraries such as react-virtualized, react-window, and react-virtuoso all include an item count property similar to the one shown in the code snippet below from material-ui. However, this property is typically located within the return statement. ...

problems encountered while trying to increment ng-click function in Angular JS and Ionic

I'm currently working on developing a quiz using Angular JS and Ionic Framework. However, I've encountered an issue: The "Continue" button is not functioning as expected when clicked (using ng-click) to move to the next question. &l ...

I'm curious about the reason behind the error message stating "Navbar is defined but never used" popping up while working with Vue

After importing the Navbar component from Navbar.vue, I attempted to include it in my app.vue. However, upon doing so, I encountered an error stating 'Navbar' is defined but never used. As a newcomer to Vue, I am unsure of why this issue is occur ...

Unfortunately, the input type number does not allow for the removal of decimal points

I need assistance with modifying the HTML code below. I want to remove the decimal point from the input field. Could anyone please provide instructions on how to accomplish this? <input type="number" min="0" step="1" ng-pattern="/^(0|[1-9][0-9]*)$/" ...

Tips for merging two applications into a single file using Node.js

This code snippet represents the functionality of my chat application. var worker = function(worker) { var http = require('http'); var fs = require('fs'); var app = http.createServer(function(request, response) { f ...

Looking for subsequence in dropdown choices with no assigned values

I need assistance with searching for a specific substring within text that is fetched from options generated by MySQL. How can I retrieve the selected option's text value in order to search for my desired substring? $(document).ready(function() { ...

Is there a method in bootstrap that reveals the elements with the hidden class?

Currently, I am loading data into a bootstrap table on my JSP. The table class is hidden at the moment. After successfully uploading the data into the bootstrap table, I have implemented the following code: $(function() { var table = $('#Table') ...

"Exploring ways to create and save content in a different root folder within a nodejs project using my

In the process of developing my npm module, I am faced with the task of creating or writing a file in either the root directory or a specific folder within the nodejs project that will be utilizing my module. This includes users who will be implementing my ...

Synchronized loops in jQuery using the .each method

I'm having trouble getting the ajaxStop function in jquery to work. Any suggestions on how to make it fire? My goal is to iterate through each anchor tag and update some content within it. After that, I want to use the ajaxstop event to trigger a scr ...

The setting `ensureCleanSession: true` doesn't appear to be effective when included in the capabilities for Internet Explorer 11

Currently, I am testing a login/logout application with the help of protractor. One challenge I am facing is dealing with a popup that appears after each login/logout scenario. In order to ensure the popup appears after each login, I need to reset the IE ...