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

Hover effect not displaying upon mouse exit

I am working on a feature where a series of images change when hovered over, with a div animating as an overlay on the image. Here is the code snippet: // hiding overlays initially $(".mini-shop .item .image a div").hide(); // toggling overlay and second ...

Struggling to organize and paginate numbers in angularjs and facing filtering and sorting issues

I'm running into some issues with getting the paging feature to work properly while applying filters. Currently, when the filters are active, the paging numbers do not display correctly and only filter the first page of results. What I'm aiming ...

Styling buttons with different colors using React onClick event.getSelectedItem() method

I am having an issue with adding a border when the class is set to "transportation active" in my React code. When I click on one of the icons, all of them become active instead of just the clicked one. This behavior is not what I want, as I only want the ...

Is there a way to eliminate a specific input box using the jquery remove function?

I've been working on some code and have run into an issue. Currently, the remove function only works on one input box that is created with the append function. I would like it to be able to work on every input box generated through the append function ...

Extract the element when the mouse is clicked

I'm currently working on developing a Chrome extension with a specific goal in mind: My aim is to capture the username when a user Ctrl-clicks on a username while browsing Reddit, and then transfer that username from the content script page to the ba ...

"An error occurred while trying to retrieve memory usage information in Node.js: EN

Is there a way to successfully run the following command in test.js? console.log(process.memoryUsage()) When running node test.js on my localhost, everything runs smoothly. However, when attempting to do the same on my server, I encounter this error: ...

Submitting a form using jquery

I am working on a project that involves using a jquery fancyzoom box. Within this box, there is a contact form that should send an email upon submission. However, I am encountering issues with calling the form submit function due to the fancyzoom feature. ...

Accelerate Image Preloading速

I am currently in the process of creating a website that features divs with background images. Although I am new to JavaScript, I am eager to learn more about it. My main goal is to preload these images so that visitors do not encounter any delays or bla ...

Is it possible to use two onChange functions in a single text field with ReactJS?

Is it possible to have two onChange functions in a single Textfield? In my code, "onChange={ showDiv}" is a handler that shows "Direct 2" when clicked and hides upon selecting option1. The second onChange={(e) => exhandleChange(e)} is used for another ta ...

Inconsistency with Mobile Viewport Problem

Apologies for the chaos below, but I've spent quite some time attempting to fix this on my own. It's time to surrender and seek assistance! Here are some screenshots to illustrate the issue: The problem is that sometimes the webpage functions c ...

Issue with VueJS: Method not displaying returned data

I am successfully able to retrieve data in the console. However, I am encountering an issue when trying to display this data on the webpage using double curly braces. The rest of the template displays fine without any issues. Template: <template> ...

Error: JSON parsing encountered an unexpected character "D" at position 1

When I call a python script as a child process from my node.js app to extract data from an uploaded file, I encounter the error 'UnhandledPromiseRejectionWarning: SyntaxError: Unexpected token D in JSON at position 1" when uploading the file thro ...

Unprepared for handling JSON data with JavaScript and jQuery

{ "Items": [ { "location": "bakery", "item1": "milk", "item2": "bread" } ], } Currently, I am encountering difficulties in parsing a JSON object and receiving the following error: Error: Unca ...

What is the best way to comprehend this asynchronous exercise with async/await?

Currently, I am working on some exercises related to async/await, and I seem to be stuck on the following problem: The function ​​opA​ should be executed before ​opB​, and ​opB​ should be executed before ​opC​. Arrange the function call ...

Is there a way to still access the data from a radio button even if it hasn't been selected?

I'm currently working on a questionnaire feature and facing an issue where I need to capture all answers, even if the radio button is not checked. Here's a snippet of the HTML code: $('input:radio').each(function () { if ($(this). ...

Having trouble receiving the response from PHP after making an AJAX request

Can you help me figure out why I'm not receiving any return value from the ajax data post? Take a look at my code and let me know where I might be going wrong. Here is a snippet of my jQuery code: $("#btnlogin").click(function(){ var email = $( ...

The problem of "undefined function appendTo" is causing issues

My jQuery code looks like this: $(function() { var productTextTemplate = $('#product-text-template').html(); var productTemplate = $('product-template').html(); var product = productTextTemplate.appendTo(productTemplate); a ...

How can I redirect to a different page with a keypress event in Next.js?

I am looking to implement a redirection function in nextjs when users press a key. There is a search input field where users can type and then hit the enter key to navigate to another page. Here's what I have attempted: const handleKeyPress = (e) = ...

Is it possible to analyze an API call and determine the frequency of a specific field?

Code: var textArray = new Array(); var allText = results.data._contained.text; for (var i = 0; i < allText.length; i++) { var text1 = allText[i]; var textHtml = "<div id='text_item'>"; textHtml += "& ...

Encountering a Module not found error with a ValidationError when trying to import an SVG file within a React

I've set up a manual Webpack 5 configuration for my React project with TypeScript. I am facing an issue while trying to import an SVG icon and using Material UI in the project. The error message I'm encountering is: Module not found: ValidationEr ...