The Vue Watch feature fails to trigger when incorporating axios

Hello everyone, I am facing an issue with my code that involves fetching data from a database using axios. The problem is that the watch function is not triggering in the .then() block. Below is the snippet of code I am currently working with. Thank you for your help!

export default {

    name: '..',
    data() {
        return {
            autocompleteOn: false
        }
    },

    watch: {
        autocompleteOn(oldVal, newVal) {
            console.log('autocomplet') // this doesn't trigger
        }
    },

    methods: {
        fetchAutocompleteResults: _.debounce((filter) => {
            let $this = this;

            let data = {
                filter: filter,
                page: $this.page
            };

            filter.resources.response = [];
            filter.loading = true;

            axios.post(BASE_URL + '/search/filter', data).then(function(response) {
                if (response.data.length) {
                    filter.autocompleteOn = true;
                    $this.autocompleteOn = true;
                    filter.resources.response = filter.resources.response.concat(response.data);
                    $this.currentFilter = filter;
                    $this.page++;
                    console.log($this.autocompleteOn); // this logs correctly
                }

                filter.loading = false;
            });
        }, 300)
    }

}

Answer №1

When using the debounce function with an arrow function, the context of this can be altered to something other than the Vue instance (such as window).

Instead of:

methods: {
    fetchAutocompleteResults: _.debounce((filter) => {

It is better to use:

methods: {
    fetchAutocompleteResults: _.debounce(function (filter) {
//                                       ^^^^^^^^        ^^^

Check out this demo:

new Vue({
  el: '#app',
  data() {
    return {
      autocompleteOn: false
    }
  },
  watch: {
    autocompleteOn(oldVal, newVal) {
      console.log('autocomplet') // doesnt trigger this
    }
  },
  methods: {
    fetchAutocompleteResults: _.debounce(function (filter) { // CHANGED from arrow function
      let $this = this;

      let data = {
        filter: filter,
        page: $this.page
      };

      filter.resources.response = [];
      filter.loading = true;
      
      // changed data for demo
      data = [{title: 'foo', body: 'bar', userId: 1}];

      // changed URL for demo
      axios.post('https://jsonplaceholder.typicode.com/posts', data).then(function(response) {
        if (response.data.length) {
          filter.autocompleteOn = true;
          $this.autocompleteOn = true;
          filter.resources.response = filter.resources.response.concat(response.data);
          $this.currentFilter = filter;
          $this.page++;
          console.log($this.autocompleteOn); // this is correct
        }

        filter.loading = false;
      });
    }, 300)
  }
})
<script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5e32313a3f2d361e6a706f69706b">[email protected]</a>/lodash.min.js"></script>

<div id="app">
  <button @click="fetchAutocompleteResults({resources: {}})">fetchAutocompleteResults</button>
</div>

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

How can we identify if the user is utilizing a text-input control?

Incorporating keyboard shortcuts into my HTML + GWT application is a goal of mine, but I am hesitant about triggering actions when users are typing in a text area or utilizing the keyboard for select menu operations. I am curious if there exists a method ...

What is the best way to retrieve the href and id values dynamically from a card in React JS?

Hello everyone, I'm new to stackoverflow and still in the process of learning how to code. Please bear with me if this question sounds like a newbie one. My question is about having dynamic values for href and id when mapping data using axios to crea ...

Error: React 404 - Unable to make a POST request with

I am new to utilizing Axios and Node.js as a backend technology. I recently inherited some React code for a login page and I'm struggling to understand why I'm unable to send a POST request to the backend. Below is my .env file: REACT_APP_BACKEN ...

Utilizing AngularJS ng-messages feature across various languages

Utilizing ng-messages to show error messages for form validation in my application. I have a multi-language app, how can I implement ng-messages to support multiple languages? HTML Form <div class="messages" ng-messages="myForm.email.$error"> & ...

Error Found in Electron webview: Unexpected token causing SyntaxError

While using my Electron application on Windows (no issues observed on Mac), I encountered an error with certain external URLs loaded into a <webview> tag: Uncaught SyntaxError: Unexpected token ... (I suspect it has to do with spread syntax). Findi ...

Generating HTML table rows dynamically in Angular based on the number of items stored in a $scope variable

In my current project, I am utilizing Angular to dynamically populate data in an HTML table. Instead of manually coding each row for display, I am in need of a solution that allows me to programmatically define each HTML row. The Angular controller snippet ...

Stopping Vue Router from re-rendering the page: Is it possible?

I am having an issue with my News.vue and News-View.vue. Whenever I navigate to news/1, it directs me to the News-View.vue page. The problem arises when there are multiple search filters (such as category, date, etc.) and infinite scroll implemented in the ...

What is the best way to combine a string that is constructed across two separate callback functions using Mongoose in Node.js?

I am facing a situation where I have two interconnected models. When deleting a mongo document from the first model, I also need to delete its parent document. There is a possibility of an exception being thrown during the second deletion process. Regardl ...

Utilizing jQuery.post to generate a dynamic dropdown menu

I recently designed a dropdown list that functions well on a standalone page. However, I encountered an issue when attempting to display it in a table on another page using jQuery.post(). The contents appear to overflow from the dropdown list. The jQuery ...

The output of the incorrect .bind() example is not as

I recently came across the .bind() method while learning JavaScript. The example I found on MDN here was quite helpful, but I decided to add some console.log() statements for better understanding. this.x = 9; // Here 'this' refers to the glob ...

Can the value of a variable be passed as seen in the JavaScript code snippet?

I'm wondering if I'm on the right track with generating random colors when a button is clicked. Here's my code: randomColor = "#" + Math.floor(Math.random() * 16777215).toString(16); // --- more code --- changeHeaderColor() { con ...

I am looking to have three rows of input text area comments instead of just one

Utilizing Bootstrap 4.3.1 with React Components I currently have this image: https://i.sstatic.net/rudsE.png And I am aiming for this design: https://i.sstatic.net/VmyTW.png comments: { elementLabel: "Comments", elementType: 'textar ...

Unable to allocate a second item to an existing one

Encountering an unusual issue while trying to assign an item a second time. Initial scenario: I am working with a jqxTree containing various items as shown below: - apple - oracle - microsoft When I drag and drop one item into another, the structure loo ...

What is the best way to duplicate/rename/replace an image in PHP while utilizing form submission and radio buttons?

I am new to PHP and I am working on a feature that allows a user to change an image using radio buttons and form submission. The goal is to copy and rename one of two image files (Open/Closed.jpg) to another location (images/status/Status.jpg) without requ ...

Discovering if an input field is read-only or not can be achieved by using Selenium WebDriver along with Java

Currently, I am utilizing selenium webdriver along with Java to create a script. One issue we are encountering is that certain fields become disabled after clicking on a button. We need to determine if these fields are transitioning into readonly mode or ...

Can the warning about a missing dependency in useEffect be incorrect at times?

After using hooks for some time, I still don't quite grasp why React insists on including certain dependencies in my useEffect that I don't want. My understanding of the 'dependencies' in a useEffect hook is as follows: You should add ...

Is it possible to set data using a React Hooks' setter before the component is rendered?

Instead of making a real API call, I am exporting a JS object named Products to this file to use as mock data during the development and testing phase. My goal is to assign the state of the function to this object, but modified with mapping. The current st ...

Utilizing *ngIf for Showing Elements Once Data is Completely Loaded

While working on my Angular 2 app, I encountered an issue with the pagination UI loading before the data arrives. This causes a visual glitch where the pagination components initially appear at the top of the page and then shift to the bottom once the data ...

Attempting to iterate over elements within an object labeled as strIngredients 1-15

event.preventDefault(); $('#mainContent').empty(); $.ajax({ url: randomDrinksURL, method: 'GET' }).then(function (response) { console.log(response); var mainContent = $('#mainContent&ap ...

Is it possible to have SVG animation triggered by scrolling?

Here's a small svg code snippet: <svg xmlns="http://www.w3.org/2000/svg" width="164.969" height="195"> <path d="M164.979 28.97a3.675 3.675 0 0 1-6.19 2.66 90.127 90.127 0 1 0-.99 132.64 3.685 3.685 0 0 1 4.95 5.46 97.5 97.5 0 1 1 1 ...