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

Is it considered acceptable to retrieve the action payload in mapDispatchToProps in a React/Redux setup?

In my MediaUpload component, I have a mapDispatchToProps function that handles file uploads. When a file is added, the onChange handler triggers two actions: creating new media entries for the files and updating the form data in the state with the generate ...

Troubleshooting Recursive Logic Problem with hasOwnProperty in JavaScript and JSON

JSON data with a specific problem highlighted by the comment // doesn't get parsed currently: var oarsObject = [{ "coordinateReferenceSystem": "26782,15851 <-- not in a value", "positionReferenceType": "geogWgs84", "geogWgs84": ...

Tips for incorporating additional filter criteria into a jquery script

I am currently utilizing a jQuery script to filter data based on date periods. However, I now need to include an additional filtering criteria for the "POSITION" column. Since I lack expertise in jQuery, I would rather accomplish this using plain vanilla J ...

Automatically refreshing the page when the back button is clicked

Within my ASP.NET application, I have two pages - Page A and Page B. When a user clicks on a link on Page A, they are redirected to Page B. However, if the user then clicks the browser's back button while on Page B, I need to force a refresh of Page A ...

Utilize AngularJS to enable the forward and back buttons to fetch JSON data, but ensure that the data is only retrieved if the item meets

I have successfully implemented forward and back buttons for paging through data items in an array from a JSON file: Controller: dishControllers.controller('DrinkcardsController', ['$scope','$http','$routeParams', ...

I seem to have mistakenly bound my conditional class to everything that was iterated in my object. Can you help me identify what I did wrong?

I recently received an object from a Last.FM API call containing the last 100 songs I listened to. If there is a song currently playing, there is a nowplaying flag on the first item in the object. I'm attempting to bind a class to the markup if this ...

How can I effectively address issues with jqGrid's sorting and paging functionality?

After making changes to the server-side code, it now looks like this: int nm = objects.ToList().Count; if (objects.ToList().Count > 0) return new PagedList(objects, nm, 1, 25, null); else return null; The JSON data has been updated as follows ...

Converting a JavaScript string into an array or dictionary

Is there a way to transform the following string: "{u'value': {u'username': u'testeuser', u'status': 1, u'firstName': u'a', u'lastName': u'a', u'gender': u'a&a ...

Multer failing to generate file during request process

My current setup involves a router and multer middleware, but I'm facing an issue where the file requested is not being created. As a result, req.file always remains undefined. const multer = require('multer'); let storage = multe ...

How come the back button does not initiate client-side navigation in a Next.js application?

In my Next.js application utilizing GraphQL to fetch articles from a server, I encountered an issue with dynamic routing when reloading the page while on an article and attempting to navigate back. The usual scenario works as expected: Index -> [slug] ...

What is the proper way to invoke render functions using Vue 3 composition API?

During my time with Vue 2, I would typically call render() in this manner: export default { mounted(){ ... }, render(){ ... }, methods(){ ... } } Now that I'm exploring Vue 3 and the composition API, I ...

Tips for retrieving next-auth authOptions from an asynchronous function

I need to retrieve values from AWS Secrets Manager and integrate them into the authOptions configuration for next-auth. The code implementation I have is as follows: export const buildAuthOptions = async () => { const secrets: AuthSecrets = await getS ...

What is the method to dynamically modify the value of location.href using vanilla javascript?

I have a button that looks like this: <button type="button" class="play-now-button" onclick="location.href='www.yahoo.com'">Play Now</button> However, I want to change the location.href value using vanilla JavaScript. The code below ...

Collaborating on interconnected documents: population dynamics and sophisticated modeling techniques

As someone who is fairly new to these technologies, I'm unsure if I am doing this correctly. I am attempting to display the name of the category in the table instead of the id (which is from the ObjectId schema field) for all the Category documents r ...

Resolving issues with JavaScript caused by Polymer updates

I am a novice when it comes to working with Polymer. From what I have gathered, there seems to be compatibility issues with Mozilla and Safari. After researching on StackOverflow, I found that adding addEventListener('WebComponentsReady', funct ...

Repairing div after upward scrolling and maintaining its fixation after refreshing the page

I have encountered two issues with this particular example: One problem is that the fixed_header_bottom should stay fixed beneath the fixed_header_top when scrolling up, causing the fixed_header_middle to gradually disappear as you scroll up, or vice v ...

What could be causing the console to display undefined?

Can anyone help me with an issue I'm having while making an AJAX call using fetch and promises? I have successfully displayed the temperatures, but for some reason, the location is showing up as undefined. Here is the code snippet: function getWeat ...

Exploring extensive collections of objects

Within my Vuex.Store, I've centralized all of the site's data in a large object. When users need to search for specific data across different pages, they require the results to be paginated. To display all of the data, I segment a particular arr ...

Convert a comma-delimited string containing a numerical value into a floating point number, for example, 3.00

I need to extract a number from a value that is returned with commas around it. My goal is to convert this value into a number so that I can compare it against another number in my code later on. However, I'm facing difficulties in reliably extracting ...

What steps should I take to ensure that my Ngrok domain is functioning properly?

Screenshot of Endpoints I've been facing challenges while attempting to get my NGROK domain operational. Despite completing all the necessary setup steps and successfully running multiple tunnels simultaneously with NSSM, as well as having a business ...