VueJS computed property not updating correctly

My web application, built with Laravel / Vue JS, includes a google map component and a Vuetify data-table component. The Vue instance also features a computed property that calculates points for the Google Map based on another computed property from the Vuetify data-table.

Code snippet of Vue Components in view blade:

<v-data-table :ref="model + 'Table'" v-model="selected" :headers="headers" :items="collection" :pagination.sync="pagination" select-all item-key="id" class="elevation-1" ></v-data-table>
<google-map v-if="mapPoints.length" class="google-map" :markers="mapPoints"></google-map>

Vue Instance code:

var app = new Vue({
el: '#app',
mixins: [ crudFunctionsMixin, adminLayoutMixin ],
data: () => ({
}),
computed: {
    mapPoints: function() {
        return this.calcPoints(this.$refs.prospectTable.filteredItems);
    }
},
methods: {
    calcPoints(items) {
        let myPts = [];
        let i = 0;

        items.forEach(function(prospect) {
            if(prospect.latitude && prospect.longitude) {
                myPts.push({
                    id:     prospect.id,
                    position: {
                        lat: prospect.latitude,
                        lng: prospect.longitude
                    },
                    index: i++,
                    title:  prospect.address + ", " + prospect.city + ", " + prospect.zip,
                    icon:   "/img/numberedMapIcons/number_" + prospect.id + ".png"
                });
            }
        });

        return myPts;
    }
}
});

The current setup throws a type error:

TypeError: Cannot read property 'filteredItems' of undefined

This error occurs because the computed property within the Vuetify data-table component has not been calculated when the GoogleMap component tries to access it.

I attempted to modify the computed property to return an empty array if "$refs.prospectTable.filteredItems" is still undefined, but this method proved to be ineffective as the computed property only gets evaluated once.

Why does the "mapPoints" computed property not update each time "$refs.prospectTable.filteredItems" changes?

An update was suggested to use a $watch variable inside the mounted() lifecycle hook instead of relying on a computed property:

mounted() {
    this.$watch(
        () => {
            return this.$refs.prospectTable.filteredItems;
        },
        (items) => {
            this.mapPoints = this.calcPoints(items);
        }
    );
}

Answer №1

Upon initialization of the Vue app, the computed properties are triggered. Keep in mind that at this stage, the component is not yet present in the actual DOM. The ref keyword acts similar to getElementById, resulting in 'undefined' if prostectTable is not defined.

During the mounted lifecycle, the components have been added to the DOM, allowing you to access the ref. Consider using a watcher for refs like prospectTable instead of a computed property.

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

What is the best way to implement CSS properties on Material UI components?

I've recently started exploring Material UI, but I'm having trouble understanding how the spacing properties function. I'm trying to utilize the "spacing" feature for various elements, but it appears that it only works for "Box" components a ...

Struggling to establish a consistent header on every page in AngularJS

I've been attempting to implement a header that appears on all my pages using AngularJS. Here is the current setup I have: In my HTML file, I've included the following code: <html ng-app="webApp"> <script src="/vendor/angular.min.js"& ...

Testing Jest with NodeJS involves simulating input from standard input (stdin)

I'm currently working on a command-line application that takes user input from standard input using the following code: const readline = require('readline'); const rl = readline.createInterface({ input: process.stdin, }); rl.on('li ...

Is there a way to make Phpstorm identify and acknowledge the usage of NextJS pages?

Just finished setting up my brand new NextJS app: function MyApp({ Component, pageProps }: AppProps) { return ( <Layout> <Component {...pageProps} /> </Layout> ) } export default MyApp However, PHPStorm keeps giving me ...

Promise and Determination failing to produce results

const { GraphQLServer } = require('graphql-yoga'); const mongoose = require('mongoose'); mongoose.connect("mongodb://localhost/test1"); const Todo = mongoose.model('Todo',{ text: String, complete: Boolean }); const ...

Angular: The Process of Completely Updating a Model Object

Within my application, there is an object named eventData which acts as a singleton and is injected into multiple controllers through a resolve function. This eventData contains various sets of data such as drop down list values along with the main model. ...

Instructions for manipulating and displaying a source array from a child component using Vue

I have a parent component with an array that I display in the template. My goal is to click on a link that uses vue-router with a dynamic id attribute, and then open a new component displaying only the element of the array that corresponds to that id. Howe ...

Changes to a key value are not reflected in the array of objects

When making changes to input fields within an array of records that include Date and Text fields in a table, the data is not updating as expected. I am encountering issues where changing the Date input results in undefined Text values, and vice versa. My g ...

When should the grecaptcha.execute() function be invoked while utilizing Invisible reCAPTCHA V2?

I recently implemented invisible reCAPTCHA successfully, but I'm wondering if I did it correctly when calling grecaptcha.execute(). After loading the API script with an explicit call like this: <script src="https://www.google.com/recaptcha/api.js ...

How can you save the output of console.log in JavaScript to a variable and then use that variable in HTML?

Here is the code snippet I've been working on. The first part consists of JavaScript code, and the second part includes HTML. $('#table').on('check.bs.table', function (e, row) { checkedRows.push({First: row.fname, Second: row ...

Click to reveal additional images once the "show more" button is pressed

Hey there! I'm currently working on implementing a feature where, upon clicking "show more", 3 images will be displayed. And if the user clicks again, another set of 3 images will appear, and so on. I seem to be facing some difficulties with the JavaS ...

Customize.Print - establish default print preferences

In my current project, I am exploring ways to add a print PDF feature. After discovering print.js, it seems like a possible solution for this task. My main concern is setting default print options to ensure the correct scale (i.e., 100%). Does print.js h ...

Order of setTimeout calls in React's execution sequence

I am currently trying to wrap my head around the functionality of this React component (which is designed to delay the rendering of its children): function Delayed({ children, wait = 500 }) { const [show, setShow] = React.useState(false); React.useEff ...

Setting up a web server with a cyclical challenge

I've encountered an issue while hosting my server.js file with the configured API on Cyclic. The deployment was successful, but every endpoint call is returning a status 500 error. Additionally, I have hosted the React front-end on github pages. I&apo ...

What is the best way to email an Excel file as an attachment using Laravel?

Here is the Excel file located in the public folder along with the directory structure: https://i.sstatic.net/DRLr5.png The name of the file is user_products.xlsx and I need to send it as an attachment. Below is the build function for the mail class: pub ...

Discovering the value of an object through its prototypes

Is it possible to create a function that can locate the value "5" within an object's prototype? What is the proper algorithm to achieve this? var rex = { "Name": "rex", "Age": 16, } te = { "to": 5, } rex.te = Object.create(te); function findValu ...

Sweet treats, items, and data interchange format

Can an object be converted to a string, stored in a cookie, retrieved, and then parsed back to its original form when the user logs on again? Here's a concise example of what I'm asking: var myObject = { prop1: "hello", prop2: 42 }; va ...

Regular expressions are used for validation purposes

I've been using the regular expression shown below to validate certain text: ^\d+(?:fs|sf)[-+]\d+[hmd]$/ Here are some sample texts I have validated with this regular expression: 20fs-4d 10sf+20m 3fs-2h So far, it's been working we ...

Angular Validation displays ng-valid when the form is actually invalid

I am currently working on a wedding RSVP form https://i.stack.imgur.com/Ct8Ux.png My objective is to hide the DONE submit button and only display it when the form is considered valid. <form method="POST" action="http://l.bheng.com:8888/wedding" acce ...

Guide to showcasing images dynamically within a table

I am currently working on a dynamic table that updates its data using a script. My goal is to also display corresponding images of the groups next to their names in the table. Whenever the group names change, I want the images to change as well. The funct ...