What could be causing the repeated calls to a computed function in vuejs?

In my Vuejs application, I start by fetching initial data and setting it in the store:

const app = new Vue({
    router,
    store,
    mounted: function() {
        var that = this;
        $.get("/initial_data/", {}, function(data) {
            that.$store.dispatch('set_initial_data', data);
        });
    }
}).$mount('#app');

Following that, I have a component defined as:

var myComponent = Vue.component('root', {
    ...
    data() {
        return {
            counters: []
        }
    },
    computed: {
        ride() {
            if (this.$store.getters.data["rides"]) {
                const that = this;

                var limit = this.$store.getters.data["rides"][0]["Movements"].split(" : ");
                that.counters.push(0);
                console.log(that.counters);
                var counter1 = setInterval(function () {
                    that.counters.splice(0, 1, that.counters[0] + 1);
                }, 10000);
                return this.$store.getters.data["rides"][0];
            }
            else {
                return "";
            }
        },
        ...
    }
});

The issue arises when not using `counter1`, causing the `ride` function to be called only once.

When including `counter1`, recursive calls are made to the `ride` function resulting in the displayed output in the console:

[0, __ob__: Observer]
all.js:196 [1, 0, __ob__: Observer]
all.js:196 [2, 0, 0, __ob__: Observer]
all.js:196 [3, 0, 0, 0, __ob__: Observer]
all.js:196 [4, 0, 0, 0, 0, __ob__: Observer]
all.js:196 [5, 0, 0, 0, 0, 0, __ob__: Observer]
all.js:196 [6, 0, 0, 0, 0, 0, 0, __ob__: Observer]
all.js:196 [7, 0, 0, 0, 0, 0, 0, 0, __ob__: Observer]

This behavior is puzzling. Can anyone provide insight into why this recursion is happening?

I would anticipate accessing the `ride` function just once as expected.

Answer №1

The reason behind this behavior is that you have utilized the setInterval function with the variable counter1, causing it to be invoked every 10,000 milliseconds.

Within the setInterval function, you are modifying the value of counter, which triggers a re-evaluation of the ride computed property.

I hope this explanation clarifies things for you.

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

Extract information from a webpage using JavaScript through the R programming language

Having just started learning about web scraping in R, I've encountered an issue with websites that utilize javascript. My attempt to scrape data from a specific webpage has been unsuccessful due to the presence of javascript links blocking access to t ...

Having an issue with the pop state function not functioning correctly

I am facing an issue with my images where clicking on a specific image changes the URL to that ID. However, I can only go back once and then the same URL is repeated every time I press the back button. Additionally, the forward button does not work at all. ...

Synchronous execution following a Node.js for loop integrated with callbacks

I'm facing a dilemma in my Nodejs application involving a for loop with callback functions. The loop iterates over an array, and for each value, an update operation is performed using a query, replacing the current value with the result of the query. ...

Submit the scaled-down form image to the server

When attempting to upload a resized image to the server, an error stating "Required MultipartFile parameter 'file' is not present" occurs. Interestingly, this error only appears when trying to upload the resized image, as uploading the original f ...

What is the best way to refine the results from an AJAX request in Datatables?

I have successfully configured a Datatables plugin, set up a new table, and populated it with content using an AJAX call: var table= $("#mytable").DataTable({ ajax: "list.json", columns: [ {"data": "name"}, {"data": "location"}, ...

Navigating Between Pages with Parameters in Ionic 2 (starter app)

I have an Ionic 2 project with a blank template containing a page that displays a list. Upon clicking on an item in the list, the user should be able to view more details about that specific item. Below are the files related to the list: list.html: <i ...

Locate specific phrases within the text and conceal the corresponding lines

I have a JavaScript function that loops through each line. I want it to search for specific text on each line and hide the entire line if it contains that text. For example: <input id="search" type="button" value="Run" /> <textarea id ...

Is there a way to preserve all the downloaded node modules in the package.json file?

Is there a way to keep track of all the node modules installed in package.json without the need for reinstalling them? I've heard about running npm init --yes, but I'm not entirely convinced if that will do the trick. Any assistance on this mat ...

ES6 destructuring in a loop

I attempted to extract the father's name from an array of objects and populate a new array with these names. Here is an example: var people = [ { name: "Mike Smith", family: { father: "Harry Smith", } }, { name: "Tom Jones ...

Creating dynamic forms using AngularJS and the ng-repeat directive

i am working with AngularJS dynamic forms . According to my userid value i generated multiple form field with same model name using ng-repeat. i am not able to get this input model values due to this ng-repeat. in this example i am using static userid data ...

Can a value of a variable be "stored" in NodeJS?

I am working on a website that allows clients to make their site go live by setting var live = true;. Once this variable is set, certain webpages will display. I would prefer not to store the live variable in a database as creating a collection solely fo ...

Challenges with exporting dynamically generated divs using jspdf in an Angular 2 project

I have been utilizing the jspdf library to print div elements in my current project. But I recently discovered an issue where dynamic content within a div is not being printed correctly. Specifically, when incorporating simple Angular if statements, jspdf ...

How can VueJS dynamically incorporate form components within a nested v-for loop?

I've encountered a challenge while working on my project. Here is the form I'm currently using: https://i.sstatic.net/LyynY.png Upon clicking the 'New Deal Section' button, a new section like this one is created: https://i.sstatic.n ...

Every time a user clicks on the map, Leaflet automatically adjusts the center

Currently, I am utilizing leaflet within Vue.js to display an image. I have incorporated custom features such as draggable boxes on the map that can be transformed into rectangle leaflet objects by leaflet. My objective is to be able to click on a rectang ...

What is the process of acquiring JSON and converting it into a JavaScript object array?

Can someone please assist me in converting the JSON generated in Spring Boot into a JavaScript object array? I'm currently facing some difficulties. https://i.stack.imgur.com/Tx5Ri.png I've been using XMLHttpRequest and my JS code is as follows ...

The dictionary of parameters has an empty entry for the 'wantedids' parameter, which is of a non-nullable type 'System.Int32', in the 'System.Web.Mvc.JsonResult' method

The console is showing me an error stating that the parameters dictionary contains a null entry for parameter wantedids. I am trying to pass checked boxes to my controller using an array, so only the admin can check all boxes of tips for a specific user. T ...

Regardless of the circumstances, the Node.js PATCH request will always run

Apologies if the title is unclear, I struggled with how to phrase it. I encountered an issue with a PATCH request designed to update a value in my database: although it returns a "working" status (200), the actual update does not occur. I have a .route(&ap ...

How do I access the previous and current values in a v-for loop in Vue.js in order to compare them?

I am working on a structural component that involves looping through a list and performing certain actions based on the items: .... <template v-for="(item, INDEX) in someList"> <template v-if="thisIsArrayList(item)"> ...

Error: Import statement is not allowed outside of module scope

I've been through multiple documentations and sources, but I'm still struggling to fix this error. I recently started learning JavaScript and decided to experiment with fetch() commands, however, I keep encountering an issue (the title). Below i ...

Is there a way to use Jest spyOn to monitor a function that is returned by another function?

I'm curious about why the final assertion (expect(msgSpy).toBeCalled()) in this code snippet is failing. What adjustments should be made to ensure it passes? it('spyOn test', () => { const newClient = () => { const getMsg = ...