Issue with VueJS: Cannot modify a component property within a watcher function

I am currently developing a Vue 2 Webpack application that utilizes Vuex. My aim is to update the local state of a component by observing a computed property which retrieves data from the Vuex store. Here's an excerpt from the <script></script> section of my component:

export default {
    name: 'MyComponent',

    data() {
        return {
            // UI
            modal: {
                classes: {
                    'modal__show-modal': false,
                },
                tags: [],
            },
        };
    },

    computed: {
        tagList() {
            return this.$store.getters.tagList;
        },
    },

    watch: {
        tagList: (updatedList) => {
            this.modal.tags = updatedList;
        },
    },
};

As evident, there is a computed property named tagList fetching data from the store. I have set up a watcher for tagList so that whenever there are changes in the store's data, I can update modal.tags accordingly.

According to the Vue documentation, I should be able to utilize this.propertyName and modify the local component state. However, when I use this.modal.tags = updatedList;, I encounter the following error:

[Vue warn]: Error in callback for watcher "tagList": "TypeError: Cannot set property 'tags' of undefined"

Why does this error occur despite following the guidelines outlined in Vue.js's documentation?

Answer №1

Avoid the use of arrow functions.

Convert from:

watch: {
    tagList: (updatedList) => {
        this.modal.tags = updatedList;
    },
},

To:

watch: {
    tagList(updatedList) {              // made a change here
        this.modal.tags = updatedList;
    },
},

The Vue documentation highlights this issue multiple times:

Avoid using arrow functions for options properties or callbacks, such as

created: () => console.log(this.a)
or
vm.$watch('a', newValue => this.myMethod())
. Since arrow functions are bound to the parent context, this will not be the Vue instance as expected, leading to errors such as

Uncaught TypeError: Cannot read property of undefined

or

Uncaught TypeError: this.myMethod is not a function

This is essentially a scope issue. When arrow functions are used, the this does not refer to the Vue instance, but rather the surrounding context where the component was declared (likely window).

Answer №2

The reason behind this problem is the scope issue. When you use this. in a different context, it doesn't have access to the data in Vue.js.

My recommendation is to modify the watch like so:

tagList (updatedList) {
    this.modal.tags = updatedList;
},

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

Trouble getting CSS and Javascript to bind when dynamically appending HTML elements

Attempting to dynamically bind HTML from an Angular controller SkillsApp.controller('homeController', function ($scope, $http, $q, $timeout) { $scope.getAllCategories = function () { $http({ url: "/Categories/GetAllCategories", ...

Transition and transition-group animations in Vue.js do not seem to be functioning correctly

Having trouble implementing CSS transitions between slides in a Vue 2 Carousel component. Slides are created using v-for and shown/hidden using v-show. Attempted to use <transition> with mode=out-in, but encountered issues with two slides displaying ...

I am struggling to figure out how to make the responsive menu close

#switch image var up = 'https://image.flaticon.com/icons/svg/149/149187.svg'; var down = 'https://image.flaticon.com/icons/svg/128/128397.svg'; $('#resNavToggle').click(function() { if ($('.resNavIcon').attr( ...

getting information from component in NextJS

Apologies if this question is too basic. I recently started my journey into learning React and NextJS. I am working on a simple application that fetches data and displays it on the Home page. In my component file, I have two functions. This component file ...

Troubleshooting: JQuery dropdown selection not updating image display

I am trying to create a select menu that changes the car image when a user selects a different model, but for some reason it is not working. Here is what I have tried: <h2 class="model">A6 <img src="images/3.jpg" id="image" width="544" height="2 ...

Implement the window.open functionality within a directive for optimal performance

I am attempting to activate the function $window.open(url, windowName, attributes); in my Angular application by using an ng-click event. I have created a directive and enclosed the window.open method within a trigger function that is connected to a butto ...

Having trouble preventing Selenium webdriver from automatically closing the safari browser

Experiencing a strange issue with Safari where it closes the browser immediately after running the code snippet below, while Chrome and Firefox behave as expected. I am using Webdriver with JavaScript for this automation. let driver = await new Build ...

What is the best way to retrieve an item using a composite key?

const dynamoDB = new AWS.DynamoDB.DocumentClient(); var parameters: any = {}; parameters.TableName = 'StockDailyCandles'; var primarykey = { 'symbol': 'AAPL', 'datetime': '640590008898' }; // sa ...

Array with multiple dimensions using commas as delimiters

My array (array[]) contains elements in the format below, separated by a comma: array[0] = abc, def, 123, ghi I want to transform this array into another multi-dimensional array (arrayTwo[]), structured like this: arrayTwo[0][0] = "abc" arrayTwo[0][1] = ...

Set the datepicker to automatically show today's date as the default selection

The date picker field is functioning correctly. I just need to adjust it to automatically display today's date by default instead of 1/1/0001. @Html.TextBoxFor(model => model.SelectedDate, new { @class = "jquery_datepicker", @Value = Model.Selecte ...

What is the best way to implement a scroll-into-view feature for a newly added list item in Vue.js?

I am currently utilizing vueJS to create a task viewing application. My goal is to make the div containing the list focus on the newly added list item immediately after adding a new task. Here's the HTML code from my template for the task list: < ...

What is the best way to incorporate a fadeIn animation to a text in jQuery?

Looking for help with appending the fadeIn() jQuery function to a string that increments an integer within a paragraph. I attempted concatenation without success. Any recommendations on how to solve this issue? $p.text(parseInt($p.text(),10) + 1); ...

The latest update of NextJS, version 13.1.4, encounters issues when implementing SCSS support with the error message "Module next/dist/compiled/sass-loader/fibers.js not

After setting up a new NextJS project, I decided to incorporate SCSS support. The guidelines provided in the documentation seemed straightforward. Following the installation instructions and including an import of SCSS as shown below: import "@/styles ...

Performing an AJAX request to a form within a CSS modal

Greetings from France, and please excuse any language errors in my English. I am currently coding in Symfony 3 and have an entity called "book" which can have different attributes (client, student, organizer, and/or speaker) based on the selected "type" a ...

What could be causing the issue with AJAX not running in a Python Django deployment on Heroku

My Django application is successfully deployed on Heroku, but I'm facing an issue with executing Ajax in the template. The Ajax functionality works perfectly fine on my local machine, however, it's not working on Heroku. I've included a snip ...

Ajax failing to trigger upon submission

I need assistance in creating a form that will first submit via AJAX before directing to a specified URL. Once submitted, an email should be sent to me through newsletter.php <script type='text/javascript'> $(function () { $("#signup") ...

What is the best way to generate a search link after a user has chosen their search criteria on a webpage?

In my search.html file, I have set up a form where users can input their search criteria and click the search button to find information within a database of 1000 records. The HTML part is complete, but I am unsure how to create the action link for the for ...

What is the best way to integrate a React component into an Angular project?

Struggling with integrating a React component into an Angular project and unable to make it work. I have a JavaScript file containing the React component that I want to use in Angular. Here's an example: React file... import React from "react"; c ...

Django not receiving data from AJAX GET request

I am attempting to transmit data stored in localStorage through an AJAX GET request to Django, but the Django server does not seem to receive it. I have verified that there is data in localStorage("preselection") as indicated by the output of console.log. ...

Retrieve both the name and id as values in an angular select dropdown

<select (change)="select($event.target.value)" [ngModel]="gen" class="border border-gray-200 bg-white h-10 pl-6 pr-40 rounded-lg text-sm focus:outline-none appearance-none block cursor-pointer" id="gend ...