When an action is dispatched, Vuex modifies two elements within the state

I am encountering an issue with my Vuex store in a Vue2 and Vuex2 setup.

Upon dispatching a specific action, it alters the state of 2 elements in my store. Here's a snippet of the state with some dummy data for clarity:

  
  {
     "clients":[
        {
           "user":{
              "id":7,
              "name":"Luis",
              "lastName":"Cervantes",
              - rest of user data -
           },
           "addresses":[
              {
                 "id":5,
                 - address data -
              },
              {
                 "id":3,
                 - address data -
              }
           ]
        },
        {
           "user":{
              "id":8,
              "name":"Richard",
              "lastName":"Czyrny",
              - rest of user data -
           },
           "addresses":[
              {
                 "id":4,
                 - address data -
              }
           ]
        }
     ],
     "client":{
           "user":{
              "id":7,
              "name":"Luis",
              "lastName":"Cervantes",
              - rest of user data -
           },
           "addresses":[
              {
                 "id":5,
                 - address data -
              },
              {
                 "id":3,
                 - address data -
              }
           ]
        },
  }

Within the state, there is a clients array.

Additionally, there is a client object that holds the currently selected client. Actions are in place to alter the client user and addresses objects separately.

Actions

SET_CLIENT_PROFILE_USER: ({commit, state}, user) => {
  commit('CLIENT_PROFILE_USER', user)
},

SET_CLIENT_PROFILE_ADDRESSES: ({commit, state}, addresses) => {
  commit('CLIENT_PROFILE_ADDRESSES', addresses)
}

Mutations

'CLIENT_PROFILE_USER': (state, user) => {
   state.client.user = user
 },
'CLIENT_PROFILE_ADDRESSES': (state, addresses) => {
   state.client.addresses = addresses
 }

Here are some computed properties used within a component:

clientsList(){
  return this.$store.getters.getClients
},
client(){
  return this.clientsList[this.client_index]
},
- more computed properties -

And here are some watchers that trigger the action dispatch:

watch: {
  'client_index': function (val, oldVal) {
    var c = this.client;
    this.$store.dispatch('SET_CLIENT_PROFILE', c);
    this.address_index = '';
  },
  'address_index': function(val, oldVal){
    - logic for dispatching action -
  }
 },

It seems that when SET_CLIENT_PROFILE_ADDRESSES is dispatched, it inadvertently modifies the addresses in both client.addresses and the corresponding clients object related to that address, instead of just changing the client.addresses part.

I am struggling to pinpoint the root cause of this behavior and am seeking a solution to only alter client.adresses.

Answer №1

In my research, I discovered that in JavaScript, objects and arrays are passed by reference to the same object rather than by value.

To address this, I opted to utilize the cloneDeep function provided by Lodash.

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

Use an external javascript file in AngularJS if permitted

To ensure that my HTML page only loads an external JavaScript file when the variable $scope.jsallowed is set to true, I attempted the following code implementation within my AngularJS based page: <script src="assets/js/slider.min.js" data-ng-if="jsallo ...

The Chevron icon is not pointing downwards even though it has already gone upwards

I want to toggle a chevron icon, but nothing seems to be happening. $("span:last").removeClass("glyphicon-chevron-down").addClass("glyphicon-chevron-up"); When I add this code below the slideToggle function without an if-else section, the icon changes to ...

Tips for transferring HTML code to a controller

Currently facing an issue while working with MVC and attempting to store HTML code from a view in a database field. In the JS section of my MVC solution, I have the following code snippet: var data = { id_perizia: $("#id_perizia").val(), pinSessione: $("# ...

Violation of Content Security Policy directive has occurred

During my full-stack project development, I encountered an issue with the inclusion of the bundle.js file in my base HTML file using a simple script tag. When trying to render the page and utilize the JS functionality, I faced a content security policy vio ...

Encountering a "Unable to use import statement outside a module" issue when trying to import react-hook-mousetrap within a Next.js project

Currently experimenting with Next.js but encountering some challenges. Recently attempted to add react-hook-mousetrap and imported it as per usual: import useMousetrap from "react-hook-mousetrap"; However, this resulted in the following error: S ...

Is the Webpack vendors JS bundle in Vue CLI containing unlisted code that is not in the dependencies or package-lock.json file?

An information security auditing tool flagged an outdated library with known vulnerabilities in our webpack-bundled chunk-vendors.js file generated using Vue CLI: The library in question is YUI 2.9.0. It appears that this library is not fully included, a ...

Creating a stunning art exhibition using React Native

Currently, I am in the process of creating a gallery component that utilizes both the scrollview and image APIs. I'm curious about how the scrollview manages its child components when it scrolls down. Does it unmount the parts that are not currently ...

Retrieve the element referred to as $el within a computed property

When attempting to retrieve this.$el.offsetTop within a computed property, the following error occurs: Cannot read property 'offsetTop' of undefined Is there a way to access the component's offsetTop in a computed method? If not, what is t ...

What is the reasoning behind storing type definitions in the @types namespace within npm?

Have you ever wondered why type definitions in npm are stored under the @types namespace which isn't directly linked to a specific organization, user, or library? Wouldn't it make more sense for npm libraries to have their types located under @[o ...

We were unable to locate the requested resource

I have been working on setting up an Express endpoint to fetch comments or reviews of a movie based on the movie ID. In my initial route, I manually passed the ID and retrieved data from TheMovieDB. However, I wanted to make this process dynamic in my seco ...

A step-by-step guide to moving Vue .prototype to its own file

I have a couple of functions that I need to add to Vue's .prototype. However, I don't want to clutter up the main.js file. I attempted to move the prototypes like this: //main.js import "./vue-extensions/prototypes"; ...

Adjusting the color of an HTML slider button as it moves

In my setup, I have a straightforward slider that I plan to use for controlling the movement of a stepper motor based on the slider's position. I wanted to give the website where this will be hosted a professional look, so I've spent quite some t ...

React Functional Component fails to update on state changes

I'm in the process of creating a React application where I can input my height and weight to calculate my BMI. The goal is to display the BMI value on a diagram. To keep things organized, I decided to break down the functionality into smaller componen ...

Obtaining the contents of a local directory with JavaScript

Currently, I am attempting to access the contents of a local folder using JavaScript. Despite my efforts with the Filesystem API, an error is consistently appearing: DOMException: It was determined that certain files are unsafe for access within a Web app ...

Node.js is great at hosting HTML files, but struggles when it comes to loading script files within those pages

Recently, I’ve been working on creating a simple login page using a mongoDB database along with Node.js and express. Since I'm still new to Node.js, I'm facing an issue that seems more complicated than it actually is. The main problem I’m en ...

Tips for designing a multi-level dropdown navbar

I am currently facing an issue with designing a navbar. I am aiming for Multi-Level Dropdowns, but whenever I click on More Services, it automatically closes the main dropdown menu. I have experimented with various approaches, but none of them seem to be ...

Sending a File Object and Data to an MVC 6 Controller in ASP.NET 5 using JavaScript

I have been working with an Ajax function that is supposed to handle file upload, but I am encountering some issues. Despite dragging and dropping the file, nothing seems to happen with the Ajax. Upon inspecting the properties on the page, I can see that t ...

Transmit the identification to angularjs for the genuine content to be displayed

I have a hidden field where I store an Id, which can also be 2, 3, 4, or 59. I need to send this Id from the hidden field to my opgaver.js file so it can download the content. However, I am facing difficulty in figuring out how to pass the Id to the opgav ...

I am interested in designing a dynamic wave-themed background for a menu

I am looking to create a menu background that ripples like a wave when hovered over. Check out the first example here: https://i.sstatic.net/LoOWM.png I want to achieve the same effect. Can anyone help me with how I can do this? <ul> <li>likk ...

What could be causing my problem with the add function?

I'm having trouble capturing the user input from modal input boxes and adding them to my state array. I've attempted to extract the values from the inputs and push them into a clone of the state array, then update the state with the clone. Howeve ...