vue2 observable mapGetters issue resolved

Having trouble iterating over mapGetters results and making changes only to a copy of the data? Here's my code snippet:

...mapGetters({
    'shop' : 'getShops'
})

When I try to iterate over the shops and make modifications, it affects the parameters in the state, impacting the entire app. I need to work on a separate copy of these getters that is still observable.

I attempted assigning the mapGetters result to a computed variable, but it still updated the state. How can I make this work as needed?

Answer №1

Below is a standard example of a store getter:

const state = {
  obj: {count:1}
}
const getters = {
  obj: (state) => {
    return state.obj
  }
}

When you access a store using either mapGetters or directly through $store.state.obj, you receive the object itself. The object in JavaScript is not immutable, meaning any changes made to it will reflect in the original store as well.

To prevent unintentional updates to objects retrieved from getters, there are two strategies:

  1. Avoid making direct modifications and only refer to or copy values when necessary for changes.
  2. Return a clone of the object in the getter function.

I personally prefer the first approach, but if you require a copy for modification (second approach), you can use the following methods to create a copy:

Using ES6 spread operator (shallow copy):

  objCopy: (state) => {
    return {...state.obj};
  }

Another option in ES6 for shallow copying:

  objCopy: (state) => {
    return Object.assign({}, state.obj});
  }

Or the ES5 method, which produces a deep copy (ensuring nested objects remain unaffected)

  objCopy: (state) => {
    return JSON.parse(JSON.stringify(state.obj));
  }

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

The navigation functionality in vue.js is experiencing issues with the router integration

As I work on securing my routers in vue.js, I have implemented user authentication to restrict access to unauthorized users. However, I encountered a loophole where a logged-in patient could access the profile of a doctor by navigating to the respective ro ...

What are the steps to customize the format of Vue3 Datepicker extensions?

Is there anyone who can lend a hand? I am currently using the Vue3 Datepicker and I have received a value that looks like this Thu Jun 23 2022 17:14:00 GMT+0700 (Western Indonesia Time) Does anyone know how to transform it into the following format? Thu, ...

Navigate array in vue-chart.js

I've been utilizing Vue-chartjs with Laravel 5.7 for my project. The goal: I aim to pass an array to Vue so that I can dynamically generate a chart by looping through specific values. My approach so far: Here's the array I'm working with ...

Error message: "The requested capacitor ionic 4 Vue project could not be found. Please check your files

After following a tutorial on Smashing Magazine about creating a new Vue project with Ionic and Capacitor, I added the necessary dependencies using yarn. However, when trying to run Electron with 'yarn run electron:start', I encountered a net::ER ...

Vue.js - Problem with loading image on screen

Although I have experience with React, I am currently facing the challenge of using Vue for a code assessment for the first time. My struggle lies in creating a reusable image component with WAI-ARIA accessibility. Despite my efforts, I cannot get the imag ...

Can you place a v-snackbar underneath a temporary v-navigation-drawer?

Is it possible to stack the v-navigation-drawer over a v-snackbar with the "temporary" prop enabled? Typically, the snackbar obeys the navigation drawer when the app prop is set, except when the drawer has the temporary prop. While this behavior may make ...

Exploring the process of searching for an id within an array of objects received through axios in Vue 2

I am currently working on verifying whether the user is included in the list that I retrieve using axios. However, I am facing an issue where the FILTER option I have used consistently returns undefined or [], even when the user does exist in the array. A ...

Is it possible for me to include additional fields in a vuetify calendar event?

Is there a method to incorporate additional fields, such as a description, in addition to the name and start/end time for an event on the v-calendar's day view? ...

What could be causing the VueJS function not to be triggered by the dropdown selection?

I created a simple component called LocaleSwitcher.vue using the Element UI library: <template> <el-dropdown trigger="click"> <div> <i class="el-icon-map-location"></i> </div> < ...

Best practices for referencing attributes created with the data method in a Vue component

In my application, there is a section that displays a list of users along with a search box to filter names. The user information is fetched from a database and stored in app.users. I have created a component named 'user' to show the details of e ...

Learn how to trigger the keydown function in VUE programming

I am trying to create a method that will be triggered whenever any key on the keyboard is pressed, regardless of where the focus is. I want to be able to determine which key was pressed in this method. Currently, I have set up an event listener for keydow ...

Error encountered in vue.js due to a ReferenceError when the resize event is used

I'm having trouble obtaining the window height when resizing, and I keep encountering the error ReferenceError: calcOfSliderHeight is not defined. Can someone explain what's happening? Here is my code: let example = new Vue({ el: '#exam ...

Synchronization between Vue and Node API on the go

Ensuring continuous synchronization with the backend API is crucial. What modifications made in the backend should automatically update the frontend in Vue? How can we achieve constant syncing with the API? Is setting intervals and calling the API the mo ...

Troubleshooting the Vue 3 Error Element Combined with a Dynamic Tab Component

I need assistance with importing Dynamic Component Content Field into my Tab using Element Plus in Vue 3. Is it possible to achieve this? Thank you for any help provided. <template> <el-tabs v-model="activeName" class="kk-tab h-20 ...

Guide on utilizing map function in JavaScript and Vue to generate a fresh array

I am working on implementing a map method in JavaScript and Vue to generate a new array of objects while only including specific items in each object. I have designed a user interface with 2 checkboxes corresponding to 2 distinct objects: <div v-for ...

What is the best way to dynamically incorporate Before After CSS code in Vue?

I am facing a unique challenge in my current project. I need to dynamically apply colors from data inside a v-for loop, specifically for the :after CSS pseudo-element. While normal CSS properties are easily applicable, I am struggling with applying styles ...

Displayable components within choices in a dropdown menu

Is it possible to dynamically update select options based on the visibility of elements in the DOM that are controlled by v-if? The current code I have does not seem to be updating the options as elements are hidden. <select class="form-control-sm fl ...

Is there a way to use HTML and CSS to switch the style of a dynamic decimal number to either Roman numerals or Katakana characters within a specified HTML element, such as a tag, div

I've searched everywhere but only found guides on list styling and counter styling in CSS that didn't work out. So, for example, I have a number inside an HTML tag that is changed dynamically using Vue Watch. I want to display the number in upper ...

What is the solution for addressing the absence of an 'Access-Control-Allow-Origin' header in the requested resource while using axios?

Here is my Vue script: <script> export default { ... methods : { login() { // uri -> http://my-app.test/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="472b28202e2978222a262e2b7a332234330720 ...

No files found in dist/ directory when using Vue.js

Beginner's Note I must confess that I am a novice when it comes to web development. Please bear with me if this question seems silly; I appreciate your assistance in advance. Initial Setup My current node version is 16.15.1 and npm version is 9.5.0 ...