Updating a nested property in the Vuex store using Vue.js code

Recently, while sharing the state across different components using Vuex store, a co-worker accidentally added a new property to the store without following the proper action dispatching or mutation committing process. Surprisingly, nothing crashed and the application continued to run smoothly. Is there any method to prevent such incidents in the future?

This is how our current store structure looks like (simplified):

import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

const store = new Vuex.Store({
  state: {
    options: {},
  },
  actions: {
    setAttributes (context, payload) {
        context.commit('setAttributes', payload);
    },
    setPrice (context, payload) {
        context.commit('setPrice', payload);
    }
  },
  mutations: {
    setAttributes (state, payload) {
      state.options.width = payload.width;
      state.options.height = payload.height;
    },
    setPrice (state, payload) {
        state.options.price = payload.price;
      },
  },
  getters: {
    options: state => {
      return state.options
    }
  }
});

And here's how the Vue instance is structured:

import Vue from 'vue';
import { mapGetters } from 'vuex';
import { store } from './store/store';

new Vue({
    el: '#app',
    store,
    computed: {
        ...mapGetters([
            'options',
        ])
    },
    mounted() {
        this.$store.dispatch('setAttributes', {
            width: 100,
            height: 80,
        });
    } 
  });

To update the price, traditionally I would have used:

this.$store.dispatch('setPrice', {
    price: 800,
});

However, we discovered that direct modification works as well:

this.options.price = 800;

Is there a way to prevent this or should we consider avoiding nested objects in the shared state altogether?

Answer №1

The insightful response was provided by Phil in the comments section, so I will share it here and mark it as the accepted solution:

To ensure stricter mode in your store, visit vuex.vuejs.org/guide/strict.html

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 clear an arrayList when an error occurs in the ajax response?

Within my code, I have initialized an empty arrayList as var selection11Data = [];. Data is retrieved from an AJAX call as shown below: var selectionId=trData.selectionId; console.log("here"); $.ajax({ url : A_PAGE_ ...

Managing the communication between Vue components

Check out my interactive code example in JSFiddle showcasing VUE field interaction: Interactive Example In this demo, I have created a custom autocomplete component, a regular input field, and a 'Load' button. The aim of the 'Load' bu ...

Improving the style of Google Maps InfoWindows for right-to-left languages

I'm currently working on a Google Maps marker infowindow and trying to adjust the padding specifically for RTL languages. Here's what I've attempted so far: google.maps.event.addListener(marker, 'click', function () { i ...

Make sure to always send back JSON data when using the default error handler in ExpressJS

I'm in the process of developing an API server using ExpressJS. I want to guarantee that the server consistently delivers JSON data rather than HTML data. While I can easily make the server respond with JSON for all customized routes, I encounter diff ...

What are the advantages of utilizing NGRX over constructor-injected services?

Have you ever wondered about the benefits of using NGRX or NGXS for an Angular application instead of constructor injected services to manage component IO? Is it simply to prevent mutation of component properties references without replacing the entire pr ...

Displaying a DIV inside an embedded DIV when selecting an option in HTML by utilizing JavaScript

My goal is to create a page where users initiate a questionnaire by clicking START in a web form - this action will open the DIV for the first question. As users answer each question (with yes/no choices), it will either display a specific DIV related to ...

Dynamically Remove One Form from a Django Formset

I have been using the following code to dynamically add a form to my formset: .html {{ form2.management_form }} <div id="form_set"> {% for form2 in form2.forms %} <table class="table table2" width=100%> ...

Updating items within a nested list in Redux can be achieved by carefully managing the state and implementing actions to add or remove

My current state is set up like this: Fruits: { 34: { FruitsID: 34, FruitsList:{apple, pineapple, banana} } } I want to update my fruit list by adding 'peach' and 'pear', while also removing 'apple&apos ...

Having trouble finding a solution to prevent code from automatically adding a class in jQuery/JavaScript?

I am currently in the process of customizing the FlexNav Plugin. I have made a modification to allow sub-menus to open on click instead of hover. However, a new issue has arisen where it requires two clicks to open a submenu. Upon investigation, I have i ...

How can I determine the size of the custom options dropdown in Magento?

I'm facing a challenging issue that I can't seem to crack. It might be because I'm still learning the ropes and struggling with technical jargon. Please bear with me as I try to explain my problem. Here is a summary of what I'm trying ...

Using Vue.js to dynamically append varying inputs upon user interaction

When I select an option, I want to display different types of inputs based on the selected option. For Example: Select input -> show input fields Select textarea -> show text areas Select boolean -> show radio buttons The Code This is where ...

Use of image tag inside the title attribute

After coming across the question on how to add an image tag inside the title attribute of an anchor tag and finding only one answer claiming it's impossible, I stumbled upon a page where it was actually done: I decided to view the source of the page ...

What is the proper way to retrieve an object from a json file?

My JSON structure looks like this: { "total": 4367, "page": 1, "per_page": 10, "paging": { "next": "/videos?query=second%20world%20war&per_page=10&access_token=XXX&page=2", "previous": null, "first": "/v ...

Pairing up with JavaScript

Currently in the process of developing a web interface for XBMC that involves ajax. Because of the limitations of our ajax functionality, I had to resort to using local resources instead of my usual ajax class which generates output. I am working with a sp ...

After updating to Angular 7, an error was encountered: "TypeError: Unable to execute map function on ctorParameters"

After updating my Angular project to version 7, I encountered a new issue. When running "ng serve --open" from the CLI, I received the following error message: Uncaught TypeError: ctorParameters.map is not a function at ReflectionCapabilities._own ...

Header Blocks that are Fixed While Scrolling in fullPage.js Sections Using the "scrollOverflow: true" Feature

I am experiencing an issue where a fixed header on my website prevents scrolling through sections when hovering, specifically when the setting scrollOverflow: true is enabled. However, everything works fine and scrolling through all sections is possible w ...

JavaScript: Uncaught SyntaxError: ')' missing after arguments in onchange event while inserting rows

I am encountering an issue with this JavaScript code. My goal is to dynamically add rows when a dropdown list's onchange event occurs. In other words, every time the 'Add more' button is clicked, a new row should be added and the textbox sho ...

What is the best way to update the current timestamp dynamically in Vue.js without needing to refresh the page?

I have a Vue application where I am using a method to retrieve the current timestamp. Although it successfully displays the current time and date, it only updates upon page refresh. I would like for it to update dynamically without requiring a page refresh ...

Converting PHP array into a JavaScript object array

I have a database table with three columns labeled as prop_no, prop_name, and prop_sc. The data from the last two columns has been extracted into two distinct PHP arrays named $propertyNameList and $propertyCodeList. I am now facing the task of transferrin ...

Using a locally hosted HTML page to update a JSON file stored on my computer

In my current project, I need to reorganize data stored in an array named unknown. Each item in this array needs to be moved either to a new array called good or another one called bad. let data = { "bad":[], "unknown": ["b", "a", "d", "g", "o", ...