Issue with updating data variable from watcher on computed property in Vue.js with Vuex

Snippet: https://jsfiddle.net/mjvu6bn7/

I have a watcher implemented on a computed property in my Vue component. This computed property depends on a Vuex store variable that is set asynchronously. Despite trying to update the data variable of the Vue component when this computed property changes, it does not seem to be working as expected.

Below is the code for the Vue component:

new Vue({
  el: '#app',
  store,
  data : {
        myVar : ""

  },
  beforeMount() {
        this.$store.dispatch('FETCH_PETS', {
        }).then(() => {
                    console.log("fetched pets")
        })

  },
  computed:{
      pets(){
        return this.$store.state.pets;
      }
    },
  watch:{
    pets: (pets) => {
      console.log("Inside watcher");
      this.myVar = "Hey";
    }
  }
});

Below is the Vuex store configuration:

const state = {
  pets: []
};

const mutations = {
  SET_PETS (state, response) {
        console.log("SET_PETS");
    state.pets = response;
  }
};

const actions = {
 FETCH_PETS: (state) => {
      setTimeout(function() { 
            state.commit('SET_PETS', ['t7m12qbvb/apple_9', '6pat9znxz/1448127928_kiwi']);
    }, 1000);
 }
}

const store = new Vuex.Store({
  state,
  mutations,
  actions
});

Here is a fiddle created for this issue. Even though the watcher is triggered when pets are loaded, the myVar data variable is not being updated as expected.

Answer №1

One important detail to note is that ES6 arrow functions do not bind the this keyword (arrow functions go beyond being just a simpler syntax for regular function). This means that in the scenario provided, the this inside the pets watcher defaults to window, resulting in myVar on the Vue instance not getting set properly. If you make the following adjustment to your code, it should function as expected:

watch: {
    pets(pets) {
        console.log("Inside watcher")
        this.myVar = "Hey"
    }
}

Answer №2

It may seem unexpected within the inner function.

Consider this alternative:

watch:{
    let me = this;
    pets: (pets) => {
      console.log("Watcher is activated")
      me.myVar = "Hello"
    }

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 possible to share a MySQL connection for cross-module usage in Node/Express by utilizing promise-mysql?

Currently, I am trying to import and utilize a database module within one of my controllers. Despite successfully establishing the initial connection, I am encountering an error when accessing any of my routes through the browser: "Cannot read property ...

What is the best method for starting a string using the symbol '~'?

Hello everyone! I have a task that requires me to add a special feature. The user needs to enter something in a field, and if it starts with the tilde (~), all subsequent entries should be enclosed in a frame within the same field or displayed in a list ...

Error: The "toString" property of an undefined variable cannot be read in uploadify

I'm having trouble with uploadify and trying to debug the issue. When attempting to use uploadify in Chrome, I encounter the following error: Uncaught TypeError: Cannot read property 'toString' of undefined Below is my html code: <li ...

The AJAX call is failing to update the state data in my React component

I've recently delved into ReactJS and encountered an issue regarding setting state while using an AJAX request. The AJAX call successfully communicates with the server, receiving a 200 code response, indicating that the API request functions properly ...

Retrieve fresh results from the search field after inputting data (nuxt, vuex)

I am currently facing a challenge with updating the search results after a user performs a new search in my Nuxt Application. The search query specifically targets users based on postcode, and all relevant data is stored in the store. Below is the code sni ...

What is the reason behind TypeScript indicating that `'string' cannot be assigned to the type 'RequestMode'`?

I'm attempting to utilize the Fetch API in TypeScript, but I keep encountering an issue The error message reads: Type 'string' is not assignable to type 'RequestMode'. Below is the code snippet causing the problem export class ...

Error: The Node Express Server is unable to locate the requested resource at "/

const http = require("http"); const myApp= require('./myApp'); const portNumber = 8080; const myServer = http.createServer(myApp); myServer.listen(portNumber) ...

Using the Play framework to showcase data in an HTML table

I have a project where I am working with multiple tables, one of which is a Person table containing id and name attributes. I have successfully retrieved the data from the database using MySql and converted it into JSON. However, I am struggling to find a ...

Observable not defined in facade pattern with RxJS

(After taking Gunnar's advice, I'm updating my question) @Gunnar.B Tool for integrating with API @Injectable({ providedIn: 'root' }) export class ConsolidatedAPI { constructor(private http: HttpClient) { } getInvestments(search?: ...

Access PHP variables in JavaScript

In my project, I have a file named english.php which holds various variable values stored in the $LANG array. For example: $LANG['value_1']="abc"; $LANG['value_2']="xyz"; In addition to numerous .php files that include require_once( ...

animation of several rows in a table with ng-animate is not feasible

I'm working on highlighting items when they appear in a table. There might be multiple items appearing simultaneously, but it seems like ng-animate is not handling this situation correctly. In the provided example below, you can observe that the div ...

Having trouble with adding a class on scroll?

My challenge is to extract the header from this website, by adding an additional class when the user scrolls at a position greater than 0. I thought it would be easy, but Java always presents problems for me. Here’s the code I came up with: <!DOCTY ...

What is the best way to display an HTML page located in a subfolder with its own unique stylesheets and scripts using Express and Node?

I am looking to display an HTML page that is located within a subfolder along with its own unique style-sheets and scripts. I am using Express and Node for this purpose, and have already acquired a separate login page that I would like to render in a sim ...

Summernote - When validating text, it is shown as raw HTML

I have integrated Codeigniter with Summernote on the frontend. In a form, if certain fields are left empty, the same page reloads for validation checking. The JavaScript and CodeIgniter code I am using is as follows: $(window).load(function(){ &l ...

The latest version of Next.js, 11.1.0, does not support monitoring for code changes within the node

In the latest version of Nextjs (11.1.0), there seems to be an issue where code changes in the `node_modules` directory are not being watched, unlike in the previous version (10.2.1). While working on a project with Nextjs 11.1.0, I have tried explicitly ...

Utilizing a single controller in multiple locations within AngularJS

I am currently working on developing an Ionic application which includes screens with lists containing checkboxes and the option to select all items. My experience with AngularJS and Ionic is fairly limited. The "Select All" functionality works as intende ...

Unable to transmit an object using ExpressJS

Greetings. I am currently trying to comprehend ExpressJS. My goal is to send a simple object from the express server, but it only displays "cannot get" on the screen. app.get("/", (req, res, next) => { console.log("middleware"); const error = true; ...

What are the methods for handling JSON type in a web server?

Hey there! I'm currently working on making an AJAX call from the browser to a web service. The data is being sent as JSON from the browser to the web service. I'm wondering if there is a different way to retrieve it as a string and then deseriali ...

The error message "Uncaught TypeError: Unable to retrieve the 'length' property of an undefined object in Titanium" has occurred

Here is the data I am working with: {"todo":[{"todo":"Khaleeq Raza"},{"todo":"Ateeq Raza"}]} This is my current code snippet: var dataArray = []; var client = new XMLHttpRequest(); client.open("GET", "http://192.168.10.109/read_todo_list.php", true); c ...

React: Show input value on button click

I have been working on a React form that displays the entered input value in a controlled input element only after the user hits the submit button, rather than updating it constantly as the user types. Here is my current solution using conditional renderin ...