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

Angular's getter value triggers the ExpressionChangedAfterItHasBeenCheckedError

I'm encountering the ExpressionChangedAfterItHasBeenCheckedError due to my getter function, selectedRows, in my component. public get selectedRows() { if (this.gridApi) { return this.gridApi.getSelectedRows(); } else { return null; } } ...

Firebase is displaying an error when using onSnapshot, specifically when a value is being waited on from an

Currently, I am working on an application where I am categorizing posts and users based on a specific room ID. I am adding a roomid property to both the user and every post. However, when attempting to fetch all posts belonging to a particular room ID, I e ...

Set the RegEx so that the entire match is non-capturing

Recently, I've been working with a regex pattern that looks like this: const newRegex = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/; const finalResult = "1988-02-01 12:12:12".match(newRegex); console.log(finalR ...

What are the steps to resolving an issue with importing a css file in next.js?

Error: ./node_modules/quill-emoji/dist/quill-emoji.css ModuleParseError: Module parse failed: Unexpected character '�' (1:0) You may need a suitable loader for handling this file type, as there are currently no configured loaders to process it. ...

Ways to resolve the issue of the experimental syntax 'jsx' not being enabled

I encountered an issue while trying to implement react-fancybox and received an error. To resolve the error, I executed the following commands: npm install --save-dev @babel/preset-react, npm install --save-dev @babel/plugin-syntax-jsx, and npm install -- ...

Mapping various sets of latitudes and longitudes on Google Maps

I am working with multiple latitude and longitude coordinates. var latlngs = [ {lat:25.774252,lng:-80.190262}, {lat:18.466465,lng:-66.118292}, {lat:32.321384,lng:-64.757370}, {lat:25.774252,lng:-80.190262}, ]; The coordinates were ret ...

Cutting an in-memory Base64 PNG using ONLY JavaScript on the client side without relying on canvas

Scenario: Working with JavaScript in a SDK environment, either on node.js or a browser. Situation: I have a base64 string containing a PNG image encoded using base64 (extracted from selenium webdriver's takeScreenshot function). Inquiry: How can I c ...

Ways to retrieve a designated object linked to a specific value within a JavaScript structure

I am facing a challenge where I need to set a javascript property object with values from another property object within the same instance. Currently, I have the following object: var PLAYER = { slides: { { slide_id: 60, slide_content: 'c ...

Creating a new row does not result in the creation of a new span displaying the character count message

Every description field should have its own character counter, with different SpanIDs displayed in respective SpanIds for each new row. How can this be achieved? <div class="row"> <div class="col-s ...

Guide on passing variables along the promise chain within a Node Express router

Upon reflection, I realized the difficulty of injecting or utilizing a variable inside the Promise scope without a surrounding object or a "this" reference to attach it to. ...

Acquire the text within an anchor tag using JavaScript

Is it possible to invoke a search for all links on my Wordpress blog? I'm not sure if my idea is correct. Currently, I am using an Ajax call for another search on this site. How can I extract the text from a hyperlink HTML tag? For example: <a href ...

Issue with AngularJS Cross-Origin Resource Sharing (CORS) when making HTTP requests, whereas standard Ajax and jQuery are

I'm currently dealing with a straightforward cross-domain service that is set up to handle Simple CORS requests. When I try to access it using a plain xmlHTTP call or jQuery($.ajax), everything works smoothly. However, when attempting to make the call ...

What is the best way to implement a new search input for my datatable while also enabling the searchHighlight feature?

I'm attempting to implement a search bar for my datatables. I need to hide the default search engine that comes with datatables, so I added a script that I found in a forum. However, when I try to run it in my code, it doesn't work and displays a ...

Confirm the value of $index and apply a specific style

Trying to figure out how to highlight a table row using AngularJS within a directive. Here is some pseudo code I came up with: if(highlight.indexOf($index) != -1) set .highlight css class Below is an example of my code snippet: $scope.highlight = [0, ...

What is the best location to store the JWT bearer token?

Exploring options for storing JWT tokens in a Bearer header token for my application. Looking for the most efficient storage mechanism. Would love some insight on how to accomplish this using jQuery. Any recommendations for a secure method? ...

Executing operations on subdocuments in Mongoose without having to fetch the parent

Currently, when I need to delete a subdocument, I follow this process: Post.findById(post_id).exec(function(err, post) { post.comments.remove({'_id': comment_id}); post.save(function(err) { res.end("Success!"); }); }); This method doe ...

Why is my NextJs app loading slowly on Safari but quickly on Chrome?

Currently, I am in the process of developing a web app using nextjs. I have encountered some issues with linking to pages, particularly the home page which contains multiple svgs and images. The performance lags when using Safari, as it does not show a loa ...

Unable to set background-image on Node (Limited to displaying only images sourced from Flickr)

I am experiencing difficulty with the background-image node property not functioning properly. In order to test this issue, I am using the "Images & breadthfirst layout" demo as an example (accessible at https://gist.github.com/maxkfranz/aedff159b0df0 ...

Canvas - Occasionally, using lineTo() can result in crisp edges in the drawing

I've created a simple Canvas drawing app. However, I've noticed that occasionally the lineTo() command generates a line with fewer coordinates, resulting in many edges: I'm currently using the latest version of Firefox - could this issue be ...

Failed attempt to perform Ajax requests for REST API data

I am currently working on developing an application that requires a login through a REST API to retrieve a session id. To achieve this, I have set up a button that triggers a JavaScript function for making an AJAX call to authenticate the user. The result ...