Observing a class getter within Vue.js

The issue at hand

I am facing a challenge in ensuring my page automatically updates when new data is available. I am using Ionic, and have a page that displays all the items collected by the user in a visually appealing manner using an ion-grid. To achieve this, I utilize a v-for loop to create a column for each element:

<ion-grid>
    <ion-row class="ion-justify-content-around">
        <ion-col v-for="item in collected" :key="item" size="5.5" @click="openDetails(item)">
            <div class="img-card">
                <img :id="`user-photo-${item.id}-${item.dType}`" :src="getSourcePhoto(item.id, item.dType)"/>
                <div class="title-holder">
                    <p>{{ formatTitle(getDiscovery(item.id, item.dType)) }}</p>
                </div>
            </div>
        </ion-col>
    </ion-row>
</ion-grid>

The collected array contains the user's items and is populated as follows:

import { UserData } from '@/internal/databases/UserData';
// Other imports 

export default {
    components: {
        IonPage, IonHeader, IonToolbar, IonTitle, IonContent, IonGrid, IonRow, IonCol, IonIcon
    },

    data() {
        return {
            collected: UserData.getCollectedChronologically(),
            getDiscovery: Utils.getDiscovery,
        }
    },

    /* ... etc. */
}

However, whenever a user adds a new item, the page does not update instantly due to caching. The newly added item gets included in

UserData.data.collected.chronologically
, but the change is only reflected after reopening the app.

Approaches attempted

I experimented with watching the method, which proved ineffective:

watch: {
    'UserData.getCollectedChronologically'() {
        console.log("Fired!");
        this.$forceUpdate();
    }
}

I also explored creating a public attribute UserData.collectedCount and utilizing the same watcher with no success. While I understand the potential of Vuex, it is not a viable solution for me. How can I resolve this persistence issue?

Answer №1

It did the trick for me

<ion-grid :key="ikey">

</ion-grid>

data() {
   return {
       ikey: 0,
       //....
   };
},

watch: {
   recschanged: function () {
      this.ikey++;
   },
   
computed: {
   recschanged() {
      return this.$store.getters.getAkinRecsAdder;
   },   
   
 
STORE.js
-----------------
getters: {
   getAkinRecsAdder: (state) => {
      return state.akinRecsAdder;
   },


mutations: {   
   mut_akinRecsAdder(state, aval) {
      state.akinRecsAdder = state.akinRecsAdder + aval;
   },
   
actions: {   
   setAkinRecsAdder({ commit }, aval) {
      commit('mut_akinRecsAdder', aval);
   },

The concept behind this is: In the state of the store, there exists the variable akinRecsAdder Whenever the length of the records changes, you must update that value.

In the component, a computed property evaluates that value The watch monitors this computed value and when it "Fires" it increments the local data => ikey++ The ikey should be the key at

<ion-grid :key="ikey">
and when altered, it triggers the rendering of the component

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

Strange flickering/visualization issue experienced with transparent MeshPhongMaterial in Three.JS

In my scene, I have a Mesh called cylinder: const cylinder = new Mesh( new CylinderGeometry(2, 2, 1, 32), new MeshPhongMaterial({ color: color, shininess: 32, opacity: 0, transparent: true, specular: 0xffff82, }), ); I made the ...

Having trouble getting ngAnimate to work properly?

I am facing an issue with ngAnimate dependency injection. For some reason, whenever I add ngAnimate as a dependency in my JavaScript code, it does not seem to work. It's definitely not the script... Here is the HTML code snippet: <!doctype html& ...

Stopping autoplay in React Swiper when hovering over it

I'm currently struggling to find a way to pause the autoplay function on swiper when hovering over it. Despite my efforts, I have not been able to locate a solution. <Swiper spaceBetween={0} navigation={{ ...

I am experiencing an issue where notifications are not appearing on my Ionic 3 device

I implemented the notification feature on my device using cordova plugin add cordova-plugin-fcm. I am working with Ionic 3. I am currently facing a roadblock and could use some assistance to resolve this issue. app.componet.ts import { Component } from ...

A guide to correctly importing a Json File into Three.js

I've been working on some cool projects in Blender and wanted to showcase one using threejs. However, I'm facing an issue where the object isn't displaying properly. Can someone guide me on how to correctly load a JSON file with keyframe ani ...

Angular custom filter applied only when a button is clicked

I have recently started exploring angular custom filters and I am curious to know if there is a way to trigger the filters in an ng-repeat only upon clicking a button. Check out this example on jsfiddle : http://jsfiddle.net/toddmotto/53Xuk/ <div ...

How can I retrieve the ngx-Summernote runtime value?

I am currently integrating ngx-Summernote into my Ionic 5 + Angular project. Is there a way to access the value using ngModel? I attempted: <div [ngxSummernote]="config" [ngxSummernoteView]="content"></div> The issue I&apo ...

Unable to access Form element in Firefox browser

I'm struggling with debugging unfamiliar problems. For instance, in my HTML there's a form: <form name="myForm" > <table> <tr> <td> <input type="radio" name="myType" value="val" onclick="someF ...

The redirection did not occur as no authorization token was detected

I have two Nodejs applications, one for the front-end and the other for the back-end. The back-end app is secured with token access using express-jwt and jsonwebtoken middlewares. My issue is as follows: when I make a request from the front-end to the bac ...

Tips for nesting maps in React without causing redundant renders

I have a list of all the items in the array let products = [ { name: "iPhone 12", storage: "64GB" }, { name: "iPhone 12 Pro", storage: "256GB" }, { name: "iPhone 12 Pro Max", storage: "512GB" ...

What methods can I employ with JavaScript to catalog data collected from an HTML form?

Currently, my form requires users to input a username that cannot start or end with a period (.). I have implemented some code but I believe there is an issue with the .value[0] parts. //Checking Username if (document.getElementById("uName&quo ...

Exploring the OAuth 2.0 integration with OpenID Connect, Loopback, and Keycloak

I'm having trouble establishing a connection to Keycloak from Loopback. I've been experimenting with the keycloak-connect library available at: https://github.com/keycloak/keycloak-nodejs-connect This snippet shows my current implementation in ...

jQuery Ajax comes with a built-in method for validating serialized forms. This method allows

After creating a form and serializing it to send to my MVC Action method, here is how my jQuery Ajax script looks: $('#submit').click(function () { var jsonObj = $('#form').serialize(); alert(jsonObj); $.ajax({ ty ...

Is there a way to dynamically update the TargetControlID of an AutoCompleteExtender using client-side JavaScript?

Typically, I am able to set the TargetControlID on the server side using code similar to this: AutoCompleteExtender ace = new AutoCompleteExtender(); ace.ID = "AutoCompleteExtender1"; ace.TargetControlID = "whatever"; While I understand how t ...

Change a nested for-loop into an Observable that has been transformed using RxJS

Currently, the following function is operational, but I consider it a temporary solution as I'm extracting .value from a BehaviorSubject instead of maintaining it as an observable. Existing Code Snippet get ActiveBikeFilters(): any { const upd ...

Vue: Develop a master component capable of displaying a sub-component

Is there a way to design a main component that is able to accept and display a subcomponent? Take the following scenario for instance: <Container> <Item/> <Item/> <SubMenu/> <Btn/> </Container> ...

Steps to create a new window using Raphael JS

Is there a way to create a new window in Raphael similar to using "_blank"? ...

The provider named toasterProvider is not recognized within the dependency injection chain, which includes toaster, RugHttpInterceptor, $http, and ng1UIRouter

Working with Interceptors to show a toast message when my app encounters an HTTP error in responseError code. Using AngularJS Interceptor for an MEAN.JS app. Interceptor Code angular.module('rugCoPro') .factory('RugHttpInterceptor', ...

What is the best method for breaking down this JSON data into distinct 'objects'?

I am struggling with deserializing JSON data into multiple instances of an object I have defined. Here is how the object is structured: function Question_Value__c () { this.Id=null; this.Name=null; this.Question__c=null; this.Order__c=null ...

Sending JSON data results

I received this JSON response: {"data":[{"series":{"id":"15404","series_code":"TOS","publisher_id":"280","series_short_name":"Tales of Suspense","start_year":"1959","end_year":"1968","published":"1959-1968","type_id":"1","no_issues":"99","published_ ...