Mastering the art of utilizing _.debounce on VueJS data modifications

I'm currently developing a small application using vue.js where I am making some post requests to an API. I have implemented the watch method to monitor changes in the API, updating the component upon successful post requests. However, as the watcher continuously checks the API, I attempted to incorporate the ._debounce method without success.

Here is the relevant code snippet:

<script>
import _ from 'lodash'
export default { 
    data () {
      return {
        cds: [],
        cdCount: ''
     }
   },
   watch: {
     cds() {
       this.fetchAll()
     }
   },
   methods: {
      fetchAll: _.debounce(() => {
        this.$http.get('/api/cds')
         .then(response => {

          this.cds = response.body
          this.cdCount = response.body.length
         })
     })
  },
  created() {
     this.fetchAll();
  }
}
</script>

Unfortunately, this implementation results in the following error:

Cannot read property 'get' of undefined

I would greatly appreciate any assistance or suggestions on what might be causing this issue.

EDIT

After removing the watch method, I attempted to add

updated(): {
  this.fetchAll()
}

This led to the request running in a loop :-/ Removing the updated lifecycle function causes the component to not respond to changes in the API or array. At this point, I'm feeling quite lost and unsure of how to proceed.

Answer №1

Take note of the following: () => { in methods causes the reference of this to be window instead of the Vue instance.

Instead, use a standard function:

   methods: {
      fetchAll: _.debounce(function () {
        this.$http.get('/api/cds/add').then(response => {
          this.cds = response.body
          this.cdCount = response.body.length
         })
     })
   },

Additional issues

There is a cyclic dependency present.

The fetchAll method is modifying the cds property (line this.cds = response.body) and the cds() watch is invoking this.fetchAll(). This results in an endless loop.

Solution: Break the cycle by eliminating the fetchAll call from the watcher:

  watch: {
    cds() {
     // this.fetchAll() // remove this
    }
  },

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

Accessing $refs in Vue.js results in an undefined value

Encountering difficulties with the reference, ref, of a tag as it is currently returning null. Excerpts from the code are displayed below: <input-layout v-if="edit" label="Status" class="" ref="statusSubtitle"> ...

A current issue lies in the fact that node.js is failing to update

I'm currently working on creating a functionality that involves reading a CSV file and checking if the headers are correct before proceeding. Below is the code snippet: let validHeaders = false; fs.createReadStream(path) .pipe(csv.parse({headers : ...

"The occurrence of a `POST` error due to failed XHR loading can be attributed to Ajax

Attempting to execute a straightforward Ajax Request to transmit a JSON object from my Javascript file to my Python file in Django has presented a challenge. Occasionally, an error message XHR failed loading: POST pops up while executing it in the manner b ...

Error: WebView element type is not valid. A valid string was expected

Here is my basic React code : import React from "react"; import { Text, StyleSheet,View } from "react-native"; import { WebView } from 'react-native'; const App = () => { return( <WebView source={{ ...

Organize multiple .env files in a folder using VueJS

Hey there, I'm currently working with VueJS 2 and my project involves multiple .env files. Each company I work with has its own .env file to customize the configuration (like skin color or files). Right now, I have all my .env files in the root folde ...

Compiling Vue.js without the need for a build tool

Vue.js is the framework I've chosen for my PHP + JS application, and I'm using the full build of Vue by directly including it via a script tag without any build tool. I'm now wondering how I can pre-compile my templates without relying on b ...

A guide to submitting forms within Stepper components in Angular 4 Material

Struggling to figure out how to submit form data within the Angular Material stepper? I've been referencing the example on the angular material website here, but haven't found a solution through my own research. <mat-horizontal-stepper [linea ...

Is there a way to direct to a particular section of an external website without relying on an id attribute in the anchor tag?

I am aware that you can link to specific id attributes by using the following code: <a href="http://www.external-website.com/page#some-id">Link</a> However, what if the external HTML document does not have any ids to target? It seems odd tha ...

Having trouble passing parameters in a Node.js express POST request?

Here is the code snippet I am currently working with: const express = require('express'); const app = express(); const bodyParser = require('body-parser'); app.use(bodyParser.urlencoded({ extended: false })); app.post('/rasp&apos ...

Exploring the consumption of jQuery with ASP.net web services

Recently, I have been exploring how to consume a webmethod using the $.ajax call with the following code snippet: $.ajax({ type: "POST", contentType: "application/json; charset=utf-8", url: "WebService.asmx/HelloWorld", ...

Getting the ThreeJs OrbitControl import version directly from the CDN

Using threejs from CDN and requiring OrbitControl as well, I encountered an issue with importing both Three and OrbitControl using the latest version 0.148.0: import * as THREE from 'https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__ ...

Steps to display the datatable footer on the printed page

I am having trouble understanding the solutions provided for my table query. The current table setup is as follows: <table class="table table-bordered make_datatable"> <thead> <tr> <th>SL No</th> ...

Managing a prolonged press event in a React web application

Hello everyone! I am currently using React along with the Material UI library. I have a requirement to handle click events and long-press events separately. I suspect that the issue might be related to asynchronous state setting, but as of now, I am unsu ...

Step-by-step guide on positioning an image to show at the bottom of a div

I am trying to create a div that covers 100% of the screen height, with a table at the top and white space below it for an image. However, when I add the image, it ends up directly under the table instead of at the bottom of the DIV. I have searched on G ...

The functionality of jQuery's appendTo method seems to be malfunctioning

I am trying to display an image with a popup using jQuery mobile. In my loop, I have the code below: for( var i = 0; i < imageArray.length; i++ ) { counter ++; // Create a new Image element var img = $('<img data-rel="popup" class=" ...

Locate the class and execute the function on the existing page

Stepping outside of my comfort zone here and I'm pretty sure what I've come up with so far is totally off. Ajax is new to me and Google isn't making things any clearer, so I was hoping someone more knowledgeable could assist! Basically, I w ...

The jQuery equalTo function is throwing an error because it doesn't recognize that the two emails are identical

Why is it that even though both email addresses are exactly the same, I still get an error message saying they don't match? The error seems to be with email2 specifically. * Email: <input type='text' name='email' /> <br/ ...

Reactive form allows you to easily format dates

Currently, the date displayed is 1/4/2022. We need it to display in the format 01/04/2022. Can we achieve this formatting using reactive forms with the sample Model form provided below? Thank you. How can we format it when starting from transactionStartD ...

Minimize redundancy in the process of adding functions to a function queue

Currently, I am delving into JavaScript animations and utilizing multiple functions to add components to the animation queue. The structure of these functions is quite repetitive as shown below: function foo(arg1, arg2) { _eventQueue.push(function() { ...

Limiting the zoom in three.js to prevent object distortion caused by the camera

I'm currently in the process of developing a three.js application where I have successfully loaded my STL objects and incorporated 'OrbitControls'. However, I am encountering an issue when attempting to zoom using the middle scroll button on ...