Display the size of the data array in VueJS once the data has been retrieved from the API

Using Vue JS, I have been attempting to retrieve data from an API. My goal is to determine the length of the array and then log it to the console using a method.

However, every time I try to do this, the value logged is always "0" instead of the actual length of the array.

Interestingly, I am able to access the data in the HTML without any issues and display the length ({{ termine.length }}).

But my ultimate aim is to achieve this using the "logToConsole" method.

It appears that there might be an issue with accessing the data which seems to be undefined at the time of function call.

I fetch the data during the "created" hook, and output the length in the "mounted" hook, so theoretically, it should be available, right?

Does anyone have any insights as to why I am unable to access the data of the array in my "mounted" function, even after successfully fetching the data during "created"?

new Vue ({
    el: "#calendar",
    data: {
        termine: [],
    },
},
created() {
    fetch("https://www.myurl.com/data/?json&function=GetEvents")
        .then(response => response.json())
        .then((data) => {
            this.termine = data;
        })
},
mounted() {
    this.logToConsole();
},
methods: {
    logToConsole: function () {
        console.log(this.termine.length);
    },
},

}

Answer №1

It is important to note that the created hook is triggered before mounted in Vue.js. When you set the termine property using an API response, this operation occurs asynchronously. If you simply assign a value to termine using a statement like this.termine = ['a', 'b'], it will log 2.

If you need to log the data after receiving the value from the API, you can use a watch function. For example:

watch: {
   termine(val) {
      console.log(val)
   }
}

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: Angular router outlet could not find any matching routes for the requested

I have been working on an application that utilizes lazy-loaded modules for each main section of the app. In one module, I have two router outlets - a primary one and one called details. const routes: Routes = [ { path: '', component: BooksCo ...

Discovering all jQuery functions employed in a JavaScript file can be accomplished through the utilization of regular expressions

I have a somewhat unconventional idea that I want to share. The project I'm currently working on has an old front-end codebase that is causing the website to run slowly, with jQuery being a major factor. My plan is to develop a tool that can analyze a ...

Scraping JavaScript Content Webpages with VBA

I'm attempting to extract a table from the Drainage Services Department website. I've written the VBA code below, but it doesn't seem to be working. I suspect that the issue lies in the fact that this particular table is generated using Java ...

Encountered an error while trying to access an undefined property during an Angular Karma

I'm currently working on testing a service function that involves multiple $http.get() calls. The function being tested returns a promise but the test is failing with an error stating response is undefined. Below is the test script: it('should ...

What is the best way to add the current date to a database?

code: <?php session_start(); if(isset($_POST['enq'])) { extract($_POST); $query = mysqli_query($link, "SELECT * FROM enquires2 WHERE email = '".$email. "'"); if(mysqli_num_rows($query) > 0) { echo '<script&g ...

Unable to modify a variable within a request

Having trouble updating a variable within a request? It seems like the variable doesn't change when it should. const request = require("request"); var all = JSON.parse(body); var steamplayer = all['response']['players']['play ...

Issue with Mongoose: Create operations are not functioning properly right after performing Delete operations

I need to refresh my collection by deleting all existing documents and then repopulating them with new data from an API call. But when I try running the delete operations first, no new documents are created. Below is a simplified version of my controller ...

reducing the dimensions of the expanding panel in Material UI

I am facing a challenge which requires me to reduce the size of the expansion panel when it is open or expanded. I checked the elements and styles tab, but it seems that we need to override the styles. Has anyone dealt with this scenario before? Here is a ...

What is the best way to update an array within an object using Redux?

I am currently working on a code for redux that involves an array. const initialState = [{ id: '1', title: '', description: '' }]; My goal is to update the array to contain two objects like this: [{ id: '1', title: ...

Encountering issues with the hyperlink tag '<a>' in an HTML document

I've encountered an issue with the code on my HTML page: <body> <div align="center"> <a href="../index.html"> <img border="0" src="banner1.jpg" width="800" height="120" alt="Ecommerce Knowledge Base"> &l ...

How can one gain access to a specifically generated element?

In my task of dynamically generating multiple elements, I am facing an issue related to accessing specific ones. To illustrate this problem as simply as possible, I have provided the following code: $(document).ready(function() { var num1 = 0; v ...

Have developers created an event trigger for when google maps controls finish loading?

While I am aware of the tilesloaded event, it appears that the controls load after this event. My goal is to use jQuery to retrieve the controls, but I am struggling to identify the appropriate event to listen for. ...

What is the best way to incorporate raw HTML code into a .jsx file within a NextJS website?

I need to integrate Razorpay code into my NextJS website, but it's currently in pure HTML format. For example, the code looks like this: <form><script src="https://cdn.razorpay.com/static/widget/subscription-button.js" data-subscrip ...

Determining the value of an element by examining the clicked element

My goal is to determine the remaining balance in my cart based on the selected item. Let's say I have 3 items in my cart, and I choose one that costs $100. Previously, I stated that I had a total of $300. In my HTML code, there are elements with IDs ...

What steps should I take to make my Vue JS delete function operational?

As I work on developing my website, I've encountered some challenges. Being new to coding, I'm struggling with creating a functional delete user button. When I click delete, it redirects me to the delete URL but doesn't remove the entry from ...

The error message "Cannot read property '$scope' of undefined" indicates that there is an issue

After receiving HTML content in an Angular app, I inject it into the HTML document but struggle to retrieve it. For example, you can see a minimized code on plunker here and in JavaScript here Below is my controller: class ReadCtrl constructor: (@$sco ...

triggering a function from a child component in React

I am facing a challenge in calling a function from the parent component that is stored in a child component. I understand how to do it from child to parent using props, but unsure about how to achieve it from parent to child. In the example below, you can ...

The persistent Bulma dropdown glitch that refuses to close

In the project I'm working on, I have implemented a Bulma dropdown. While the dropdown functions correctly, I am facing an issue when adding multiple dropdowns in different columns with backend integration. When one dropdown is open and another is cli ...

Learn how to dynamically insert an element into an angular scope using a click event

Currently, I am working on a function called onGroundUserClick within the Scope passedScope. The goal is to have a function triggered upon the completion of loading the iframe that will establish ng-click. var $tdName = $("<td/>", { ...

Angular error ReferenceError: $Value is not defined in this context

As a newcomer to AngularJS, I am facing an issue while passing a list from the HTML file to the backend for processing. The error message ReferenceError: $Value is not defined keeps popping up. Within my controller file, I have a function named test. The ...