Issue stemming from reactivity causing difficulties with Vuex data mutation within actions

I have a Vuex store action that needs to interact with the API using new data for updating purposes.

My goal is to create a separate object that mirrors an existing value in the store, allowing me to manipulate it without affecting reactivity.

However, when I attempt to use Array.push(), I encounter the following error:

Do not change vuex store state outside of mutation handlers

Is there a different approach I should take?

(Possibly related to my getter on

rootState.phone.policy.currentPolicy.attributes.insured.phones
which might be causing this issue).

  async [PolicyActionTypes.UPDATE_POLICY](
    { rootState },
    payload: UpdatePolicyPayload
  ) {
    const newPolicy: Policy = {
      ...rootState.phone.policy.currentPolicy,
    };

    const newPhone: Phone = {
      imei: '123',
      brand: 'Samsung',
    };

    newPolicy.attributes.insured.phones.push(newPhone);

    // Simulated asynchronous API call
    api.updatePolicy(newPolicy)
  },

Answer №1

When you spread values, you're essentially creating a shallow copy, which means you are still pointing to the original object.
If you make changes to the copied object, it may seem like you have a deep copy, but in reality, it's still referencing the initial one.

For more detailed information, check out my full explanation.

In short: Use cloneDeep if you want a true deep copy of an object.

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

Enhance the MUI palette by incorporating TypeScript, allowing for seamless indexing through the palette

When utilizing the Material UI Palette with Typescript, I am encountering a significant issue due to limited documentation on MUI v5.0 in this area. Deep understanding of typescript is also required. The objective is to iterate through the palette and vir ...

Creating a Custom Validator in Vuejs that can verify each attribute of an object within the props

I have an object called car in my props, and I need to validate each attribute of this object. Here are the rules: color must be either white or black name must be a String numberOfSits should be between 2 and 4 status must be either Available or Not Avai ...

What is the process for installing vue-cli?

I'm currently diving into the world of Node Package Manager and Vue, trying to wrap my head around the Vue CLI. On the vue.js website, they provide instructions for running the official Vue CLI: https://i.stack.imgur.com/0OCrc.png I have a few inqu ...

Incorporating a parameter into a <div> only when the parameter holds a value

Being new to web development, I have a rather basic query. If the datainfo prop variable is not empty, I'd like to include a data attribute in the div tag. <div style={{height: props.height - handleHeight()}} data={datainfo ? datainfo : ""}> C ...

Type '{}' is lacking the subsequent attributes in type 'Record'

This is the code snippet I am working with: const data : Record<MediaType, Person[]> = {}; I encountered an error while initializing the 'data' object as shown above. The error message specifies that certain properties are missing from typ ...

Ways to obtain a referrer URL in Angular 4

Seeking a way to obtain the referrer URL in Angular 4. For instance, if my Angular website is example.com and it is visited from another PHP page like domaintwo.com/checkout.php, how can I detect the referring URL (domaintwo.com/checkout.php) on my Angul ...

Passing a React functional component with SVG properties to another component as a prop

My goal is to import a React functionComponent from an SVG and pass it as a prop to another component for rendering the svg. The code below compiles without errors, but crashes when trying to display the svg in the browser with the following message: Er ...

How to choose `optgroup` in Vue 1.x

In previous iterations of vue.js, developers had the ability to generate a dynamic select list utilizing optgroups similar to the example found here. In the latest versions of vue, the documentation suggests using v-for within the options instead of optgr ...

The code inside the promise .then block is executing long before the promise has completed its

After spending quite some time working on this messy code, I finally have a functioning solution: loadAvailabilities() { let promises = []; let promises2 = []; let indexi = 0; //return new Promise((resolve, reject) => { this.appo ...

What is the method to extract a value from the $emit payload using Vue.js?

I have a situation where I am sending an event with different values from my ConversationList component (child) to the ConversationModel component (parent). Conversation List getConversation(conversation_id, receiver_id, username, avatar){ this.$emit(& ...

The v-list-group does not automatically expand sub-groups based on the path specified in the group prop

I have a navigation sidebar that includes nested v-list-groups. Based on the documentation, the "group" prop of v-list-group should expand based on the route namespace. To see more information, visit: https://vuetifyjs.com/en/components/lists/ While this ...

Looking for a way to connect a background image in Vue CLI?

When running the code below, I encounter an issue. The code runs properly but the images are not displaying and instead showing the URL as unknown. How can I fix this problem? The images definitely exist. <template> <div class="slider">< ...

OracleDB Error: NJS-067 - A precompiled binary for node-oracledb was not located for the win32 architecture variant

I am having trouble installing node-oracledb for a 32-bit target in my electron application based on Vue. I have searched at https://github.com/oracle/node-oracledb/releases, but couldn't find any pre-built versions. Here is the command I used: npm in ...

Cleve js does not include delimiters in its date output

In my Vue.js project, I decided to implement a date input field using cleave.js. After passing the following options: options="{date: true, delimiter: '/', datePattern: ['m', 'd', 'Y']}" I encountered an issue wh ...

Retrieve all the Firebase keys within a Vue script using Vue-Firebase

Trying to understand Firebase's handling of entries, I've been attempting to retrieve all keys from a child node. <div v-for="item in TeamArray"> {{item['.key']}} </div> Retrieving the keys from the HTML section works ...

Group multiple typescript files into separate outFile modules

Can TypeScript files be grouped into multiple outFiles? I want to bundle my Typescript code, but instead of one single JS file, I would like to organize my TS into separate JS files such as controllers.js and plugins.js. The options in the TypeScript pro ...

Error: The "issuerBaseURL" parameter needs to be a properly formatted URI

The Vue app is experiencing difficulty loading and keeps showing an error related to the issuerBaseURL, stating that it must be a valid URI. No matter what changes I make, the issue persists. I have been following this tutorial: https://auth0.com/blog/co ...

Using TypeScript in conjunction with Node.js

I'm currently trying to use typescript with nodejs, but I keep encountering errors. Can anyone help me troubleshoot? Here is the code snippet (assuming all necessary modules are imported): import routes from "./routes/routes"; let app = express(); ap ...

Navigating through a nested array within a JSON object using Vue.js - a guide

I have a JSON data array that includes outer and inner subarrays. My goal is to loop through both levels and create a table. Below you'll find a snippet of the sample array: { class:'I', subDdiv:[ { ...

Divide Angular component unit test involving asynchronous tasks

One of my components is responsible for fetching data from a server using a service and then displaying it. I have created a test for this component which ensures that the data is loaded correctly: ... it('Should contain data after loading', as ...