What are the drawbacks of setting data from computed properties?

When working with vuex, I often come across a scenario where I receive an object like the following:

user: {name: 'test'}

In my app.vue file, I access this object using this.$store.getters.user

computed: {
   user: function() {
       let user = this.$store.getters.user
       return user
   }
}

I also need to set a data property called 'this.name'

data() {
   return {
      name: ''
   }
}

computed: {
   user: function() {
       let user = this.$store.getters.user
       this.name = user.name
       return user
   } 
}

However, when linting, I encounter the error 'unexpected side effect in computed property'. The 'name' data should ideally be used as a v-model for updating API parameters. While I understand that it can be ignored if you are aware of what you're doing, I am curious as to why this error is triggered and how to handle it effectively.

Answer №1

Avoid assigning values directly in computed properties. If you want to access the name of a computed user, create a new computed property:

   user: function() {
       let user = this.$store.getters.user
       return user
   },
   name: function() {
       if(this.user.name!=undefined) return this.user.name
       return ''
   },

Do not store the name in the data section.

If it is absolutely necessary to set the name, utilize a watch on the user object and update the name property accordingly:

watch: {
   user(newVal) {
      if(newVal.name!=undefined) this.name = newVal.name
   }
}

Answer №2

Vue offers both computed getters and setters. When you define a computed property like the one above, it acts only as a getter. A getter is designed to simply retrieve a value and should be a "pure" function without any side effects, making it easier to understand, debug, and test.

According to the documentation for the rule that triggered the linting error in your code:

Introducing side effects inside computed properties is strongly discouraged. It leads to unpredictable code behavior and makes it difficult to comprehend.

In your scenario, considering utilizing a computed setter for either the user or name values to enable using them with v-model. One approach could be:

computed: {
  user: function () {
    return this.$store.getters.user;
  },
  user: {
    // getter
    get: function () {
      return this.user.name;
    },
    // setter
    set: function (newValue) {
      this.$store.commit('setUserName', newValue);
    }
  }
}

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

Send a bundle of data through AJAX requests

An issue has been encountered on an HTML/PHP page named sucessful.php where a variable job_id passed from another page is not being received by the destination page interview.php. The problem arises when attempting to transfer two variables and their corr ...

Error: Attempting to assign a value to the 'firstData' property of an object that is undefined

I am encountering two identical errors in my service. Below are the details of my service and controller: Service code snippet: getData: function (dataRecievedCallback, schemeid, userid) { //Average JSON api averageData = functi ...

How can I utilize the <v-for> and <v-checkbox> components in Vuetify to create a table format with multiple checkboxes displayed

Utilizing the VuetifyJs framework for VueJS, my goal is to showcase a checkbox in a table format based on an array of objects. The Desired Output looks like this: https://i.sstatic.net/veXGZ.png When 'All Users' is selected, all checkboxes shou ...

Customize Your Calendar: A Guide to Disabling Dates with Pikaday.js

Wondering how to disable specific days on a calendar? Look no further! Here's a solution using the `disableDayFn` option from Github: disableDayFn: callback function that gets passed a Date object for each day in view. Should return true to disable s ...

Tips on saving php variable content in HTML "id"

Three variables are used in PHP: message_id, message_title, and message_content. Their content is stored inside HTML 'id' for later use with jQuery. Example: Variables: $id_variable = $rows['id_mensagem']; $message_title_edit = $rows ...

I have a specific resolution in mind where I want to run jQuery code during window scrolling

I have a jQuery code that I want to run only when the resolution is greater than 950px. If not, I risk losing the responsive logo. My goal is to create a navigation bar similar to the one on the Lenovo homepage. $(document).ready(function(){ //left ...

Enhancing Vue with Vueify and Babel 7

I am currently utilizing a combination of Gulp, Browserify, Vueify, and Babel for my vue.js project development. My hands are tied to using Gulp as the build system and unfortunately, I had to upgrade from Babel 6 to Babel 7 due to the integration of Jest ...

Discover how to achieve the detail page view in Vue Js by clicking on an input field

I'm a beginner with Vuejs and I'm trying to display the detail page view when I click on an input field. <div class="form-group row"> <label for="name" class="col-sm-2 col-form-label">Name</label> ...

Conceal the rating of WordPress products when they have no ratings

I am looking to remove the star ratings under the title for products with empty reviews. I specifically want to hide the stars without allowing users to leave a new review. I found a similar solution for hiding a different element and attempted to customiz ...

Ways to analyze users who have clicked a button

After a user registers, they are automatically taken to /proto where they can view a list of animals available for adoption. However, the challenge lies in identifying the specific user who clicked the button (as this information must be associated with th ...

Exploring the capabilities of chromaprint.js within a web browser

I'm currently in the process of developing a music streaming platform and I'm looking to include the chromaprint.js library for deduplication purposes. In my workflow, I utilize browserify and gulp. Despite the fact that the library claims it ca ...

Guide on how to retrieve a response from an API Route and integrate it into the client side of the app router within Next.js

Transitioning from Next.js 12 to 13 has been quite perplexing, especially when it comes to handling JSON data. Every time I attempt a fetch request, I find myself needing to refer back to documentation due to the confusion surrounding JSON. Is there anyone ...

Is there a way to dynamically send a Vuex getter as a prop to a child component?

To dynamically pass an array into my component's prop, I am fetching the array using a getter. This is necessary because I have multiple lists fetched from the store and I want to pass them down using a loop. Parent.vue (refer to line: 2) <v-tab- ...

Is there a way to retrieve the $state object from ui router in the console?

I attempted to modify the route from the console by using this method to access the $state object: $inject = angular.injector(['ng', 'ui.router']); $inject.get('$state').go Unfortunately, I encountered an error: Uncaught Er ...

Iterating through elements to set the width of a container

I am currently working on a function that dynamically adjusts the width of an element using JavaScript. Here is my JavaScript code: <script> $('.progress-fill span').each(function(){ var percent = $(this).html(); if(per ...

Having trouble installing gulp locally due to an error with ` ode_modulesansi-regex`

While attempting to set up Gulp on my Windows 10 system, I encountered an error during the local installation process. $ node -v v9.10.1 $ npm -v 5.6.0 I successfully installed Gulp globally: $ npm install --global gulp-cli $ gulp -v CLI version 2.0.1 ...

How come I am unable to save an array of objects in a State within React JS?

React JS component: When I make a request to the backend to fetch data stored in a MySQL table, it returns an array of objects. I store this data in a state called `favcoin`. However, when I console.log(favcoin), it displays an empty array [ ]. Strangely, ...

Sending Component Properties to Objects in Vue using TypeScript

Trying to assign props value as an index in a Vue component object, here is my code snippet: export default defineComponent({ props:{ pollId:{type: String} }, data(){ return{ poll: polls[this.pollId] } } }) Encountering errors wh ...

Troubleshooting Tips for Resolving Problems with VueJS getElementById Bug

I'm currently working with a VueJS single File component that has the following template: <template> <div class="row"> <div class="col-md-12"> <div id="hottable"></div> < ...

What is causing the col divs to stack instead of aligning next to each other?

I am a newcomer to Vue.JS and front-end programming in general. I wanted to create a page with a fixed sidebar and content below a navbar. Here is the configuration I tried: <template> <div class="container-fluid"> <div class ...