Vue computed property does not reflect updated value

I'm attempting to modify a Computed Property that receives its data from the vuex state.

The data is retrieved from the store. I aim to update the value allowed in the store. But, when I click on my update button, the value does not get updated.

Here is the HTML snippet:

<div @click="update">update</div>
  <b-row>
    <b-col v-for="cat in categories" :key="cat.id" sm="12" md="6" lg="4">
        <div>{{cat.allowed}}</div>
    </b-col>
  </b-row>
computed: {
...mapGetters("categories", ["customerCategories"]),

 categories() {
   return this.customerCategories;
 },
 methods: {
    update() {
      this.categories.filter((element) => (element.allowed = true));
      console.log(this.categories); // value of allowed is not being updated
},
 }

,

// Data retrieved from the store
categories = [
  {
    allowed: false,
    description: "hsdkj fskdjf skfj",
    id: 15
  },
  {
    allowed: false,
    description: "blah blah",
    id: 13
  },
   {
    allowed: false,
    description: "more blah blah",
    id: 13
  },
  {
    allowed: false,
    description: "lots more blah blah",
    id: 1
  }
]

Despite trying to target and alter the vuex code, the value is still not updating as expected.

 const data = [...this.categories];
  const l =[];
  const updated = Array.from(data);
  updated.forEach(res => {
    res.allowed = 'boo';
    l.push(res);
  });
  console.log(l);

Answer №1

It is recommended to ensure that you are updating your state within Vuex and retrieving the updated value using computed properties. Computed properties are not reactive by default, so changing them can be challenging. If you need to modify a computed property, you should define both a getter and a setter. A more efficient approach would be to create an action that mutates your state, and then sort the data in your getters.

Answer №2

It is important to follow good practices when modifying the store state. Instead of directly changing the state, utilize a Vuex mutation to update the store in a controlled manner.

To define a mutation that updates state.categories, you can structure it as follows:

// store.js
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  modules: {
    categories: {
      namespaced: true,
      ⋮
      mutations: {
        SET_ALLOWED(state, value) {
          state.categories.forEach(c => c.allowed = value)
        },
      },
    },
  },
})

In your component, invoke the mutation using commit():

// MyComponent.vue
export default {
  ⋮
  methods: {
    update() {
      this.$store.commit('categories/SET_ALLOWED', true)
    },
  },
}

View a live demonstration here.

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

Using JavaScript promises in conjunction with if/else statements

When I utilize the filemanager function for a directory (/), everything runs smoothly. However, if I try to call a file (/index.html), it returns an error. I have identified that the issue lies within the if/else statement (the readdir function executes e ...

How do I programmatically switch the Material-UI/DatePicker to year view in React?

I have a DatePicker component set up in my project, and it works perfectly fine. However, for my specific use case, I only need the year view to be displayed. Within the child component of the DatePicker (Calendar), there is a function called: yearSelect ...

Issues encountered when using .delay() in conjunction with slideUp()

Issue: The box is not delaying before sliding back up on mouse out. Description: Currently, when hovering over a div with the class ".boxset" called "#box", another div "#slidebox" appears. Upon moving the mouse away from these two divs, #slidebox slides ...

Embedding JavaScript code from a user control within an UpdatePanel

Upon the initial rendering of the page, the initializeControl function is executed successfully. Similarly, when a full post-back occurs (e.g., via a submit button), the initializeControl function is triggered and everything functions as intended. Howeve ...

What is the best method to "deactivate" a radio button while ensuring that a screen reader can still read the text and notify the user that it is inactive?

My current situation involves needing to deactivate certain radio buttons, while still having the option to reactivate them later. When I use the disabled attribute, screen readers will overlook this field and miss key information. I am seeking an accessi ...

What causes the error message "React not defined" to appear in my code?

When attempting to use the Chrome browser console to create a var boldElement = React.createElement('b');, I am encountering an error message: Uncaught ReferenceError: React not defined. What could be causing this issue? ...

What is the best way to utilize external, customizable scripts within Nuxt.js?

I'm in the process of developing a Nuxt website and I need to be able to edit a specific JavaScript file after building in order to update the content of a table. Does anyone have any suggestions on how I can achieve this? So far, my attempts to incl ...

Effortless sliding panel that appears on hover and vanishes when mouse is moved away

I am in the process of creating a menu for my website that utilizes linkbuttons which trigger additional linkbuttons to slide down upon hover. The desired effect is a smooth sliding panel that appears when hovering over the linkbutton, and disappears when ...

Tips for sending a JavaScript object from PHP to AJAX

I've been racking my brain for hours, scouring through countless articles, but I'm still unable to crack this puzzle. Here's the situation: I'm currently tinkering with Chrome extensions and I need to make a server call that will fetch ...

Submitting data in an android app using the HTTP POST method and

I need to translate this HTTP POST request from JavaScript to Android. I'm facing an issue with cids: []. I am unable to create a JsonObject with the square brackets symbol [ ] as it should be an empty array. This is my original JavaScript code: va ...

Selectize autocomplete causing a postback upon pressing the backspace key

Currently, I am integrating Selectize.js into my ASP.NET WebForms project. To enhance user experience, I am transforming an ASP.NET Server Side DropDown into an autocomplete dropdown using this plugin. This dropdown is connected to a DataSet with text and ...

Issue with Three.js: GLTF model not positioned correctly at origin point

After attempting to load a glTF model with a 0,0,0 position, I noticed that it appears far from the origin. Upon trying to rotate the glTF model, I observed that it spins around (indicated by blue dots) the origin instead of spinning from its center. Thi ...

Show the child div using JavaScript when hovering over it

I am currently working with the following HTML structure: <div id="wrapper"> <div onmouseover="displayDiv()"> <div id="thisIsTheDivToDisplay"></div </div> <div onmouseover="displayDiv()"> <div id="thisIsT ...

AngularJS: How can components effectively communicate with each other using best practices?

I've been struggling to figure out how to facilitate communication between components. The primary question that has stumped me is: when should I opt for $watch versus $on ($broadcast/$emit) to establish component communication? I've identified ...

The functionality of using an Ajax call to invoke a php function on the same page is not functioning correctly

I am facing an issue where Ajax is not working in the same PHP file as the PHP function I want to call. My goal is to have a button that, when pressed, will trigger the function without reloading the page. I have placed my Ajax script at the bottom and the ...

The most effective method for transferring values from PHP to Javascript

Currently, I am in search of the most effective way to transfer data such as arrays, objects, and JSON values from PHP to JavaScript. Up until now, I have only come across the following method: PHP - json_encode(value); JavaScript - eval() Anot ...

Separating SailsJS View Layer with Added CSRF Protection

I have been pondering the idea of completely decoupling a sailsJS app from its View Layer. This would involve managing templates, views, client-side JS, and assets separately from what is solely intended to be a RESTful API in my scenario. I am considering ...

Utilizing navigation buttons to move between tabs - material-ui (version 0.18.7)

I'm currently using material ui tabs and attempting to incorporate back and next buttons for tab navigation. However, I've run into an issue - when I click the back or next buttons, the tabs do not switch. Here is my existing code snippet: ... ...

What is the best way to utilize a CSS framework for just one component in my React application?

I am currently working on a large portfolio project in React and I want to avoid the hassle of rebuilding the entire project just because of a styling framework. The issue I am facing is that when I use Materialize CSS Framework, it affects other parts of ...

Using Spry Validate for form validation in conjunction with Ajax submission

I'm currently facing an issue where I want my form to validate before the ajax call is made, but I can't seem to figure out the correct coding for this process. When I separate them, I am able to either post using ajax without validation or with ...