Dealing with unanticipated consequences in computed attributes - Vue.js

I am facing a challenge while working on the code below. I am attempting to utilize the getTranslation object to match values from the originalKeys array and then add these values to a new array called allKeys.

However, ESLint has flagged an error stating,

Unexpected side effect in "getkeys" computed property.

I have attempted moving the getkeys function to methods, but it seems impractical to call a method every time for translation. How can I resolve this issue?

<template>
    <select v-model="selected">
    <option v-for="key in getkeys" v-bind:key="key"> {{ key }}</option
    </select>
</template>

data(){
    return{
    selected: '',
    allKeys: [],
    originalKeys: [],  //e.g. ["ALPHA_MIKE]
    getTranslation: {} //e.g. {"ALPHA_MIKE": "ALPHA MIKE"}
    }
},
computed: {
    getkeys(){
        let tableHeaders = [];
        for( var i=0; i<this.originalKeys.length; i++){
            let translation = this.getTranslation[this.originalKeys[i]];
            tableHeaders.push(translation);
        }
        this.selected = tableHeaders[0]; //unexpected side effect here
        this.allKeys = tableHeaders; //unexpected side effect here.
        return this.allKeys;
    }
}

Answer №1

In my previous comment, I mentioned that it is not recommended to modify other data in the computed property; instead, you should utilize the watch method.

computed: {
    fetchKeys(){
        let headerList = [];
        for( var i=0; i<this.originalKeys.length; i++){
            let translateData = this.getTranslation[this.originalKeys[i]];
            headerList.push(translateData);
        }
        return headerList;
    }
},
watch: {
  fetchKeys: {
    deep: true,
    handler: function (newData) {
      this.selectedKey = newData[0]
      this.allTableKeys = newData
    }
  }
}

Answer №2

It has been mentioned in previous responses that the reason for this issue is due to directly modifying the original data within a computed property. To resolve this, it is recommended to utilize a method instead.

methods:{
    updateKeys(tableHeaders){
        this.selectedHeader = tableHeaders[0];
        this.allTableHeaders = tableHeaders;
    }
},
computed:{
    retrieveKeys(){
        // Your code...
        this.updateKeys(tableHeaders);
    }
},
data: function(){
    return{
        // Your data...
    }
}

Answer №4

If you follow my recommendation, you should consider moving the allKeys array to a computed property and eliminating the unnecessary use of tableHeaders and getKeys:

<template>
    <select v-model="selected">
    <option v-for="key in allKeys" v-bind:key="key"> {{ key }}</option
    </select>
</template>

data(){
    return{
    selected: '',
    originalKeys: [],  //e.g. ["ALPHA_MIKE]
    getTranslation: {} //e.g. {"ALPHA_MIKE": "ALPHA MIKE"}
    }
},
computed: {
    allkeys() {
        return this.originalKeys.map(key => this.getTranslation[key])
    }
}

It may not be necessary to include this.selected = tableHeaders[0] as the first option will be automatically selected by default.

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

Issues Persist with Vue CLI 3 and Axios - Proxy Server Failure

My VueCLI frontend application is running on http://localhost:8080 in development mode. I encountered a CORS issue when trying to access API services from http://localhost:36856. Despite setting up proxy server configuration in vue.config.js, the problem p ...

Transfer the HTML5 FullScreen (MAP) feature onto a separate display

I'm trying to integrate a leaflet map into my AngularJS Application, but I've hit a roadblock. My goal is to move the Fullscreen feature of the Map to a second screen (if one is available), allowing users to interact with the application on the ...

There was an issue with the Vuejs Router that prevented the property '$emit' from being read due to a TypeError because

I am facing an issue with a router configuration like this: { path: 'user', redirect: '/user', name: 'user', component: { render(c) { return c('router-view', { on ...

Using Fabric.js to manage image controls situated beneath another overlay image

I'm currently working on a canvas user interface using jquery and the fabric.js library. I managed to add an overlay png image with transparency by implementing the code below: var bgImgSrc = bgImg.attr('src'); canvas.setOverlayImage(bgImgS ...

What advantages come from caching the document object for improved performance?

Usually, I cache DOM objects used in a script. However, recently I found myself having to reference the document object within a jQuery wrapper. I started questioning whether caching $(document) is necessary since there's only one document object per ...

Endless scrolling with redux and react

I'm facing an issue while trying to implement infinite scroll in a React-based application that utilizes Redux for state management. I am attempting to dispatch an action on page scroll but have been unsuccessful so far. Below is my code snippet: // ...

Top method for communication between vue.js and a python script

Currently, I am exploring the most effective approach to execute a Python script based on user input in a Vue application. One solution I discovered is creating an API with Flask that can execute the desired Python script and then using a curl request to t ...

Error: Unable to access 'createInvite' property from undefined variable

Having trouble generating an invite to one of my guild's channels. Here is the code snippet I am using: const { Client } = require("discord.js"); const client = new Client({ intents: [] }); client.on("ready", async () => { ...

Unpacking nested objects using dynamically generated property names in a React state - a guide

Having trouble with using setState and figuring out how to destructure the object with a dynamic property name, denoted by id. The state looks like this after computation: { "inputConfig": { "5d4d684cadf8750f7077c739": { "0": "5d4d ...

Top method for showcasing animated images (HTML/CSS/JS)

For my website, I want to create an engaging animation showing a coin being flipped multiple times in the air before landing on a specific side. After the animation finishes, I would like it to transform into a static image of the final result. I've ...

Troubleshooting issues with cross-domain jQuery ajax requests

Struggling with this code and unable to make it work. This call consistently returns a "Failed to load resource: the server responded with a status of 401 (Unauthorized)" error message. $('#btnZendesk').click(function () { $.ajax({ ...

How to make the dropdown menu in Material UI Select have a horizontal scroll bar?

I've run into an issue in my project with the material ui Select component. The dropdown contents are too long and don't fit properly. To solve this problem, I tried adding a horizontal scroll to the dropdown menu by setting OverflowX property i ...

What is the reason behind Intellij Code Inspection indicating that a selector is not being used?

I have a small project consisting of two files located in the same folder. App.css .App-align-left { text-align: left; } App.js import React from 'react'; import 'App.css'; class App extends React.Component { constructor(p ...

Vue-loader component experiencing issues with applying dynamic CSS styling

I'm working with a Vue Component and I want to enhance it by binding a color to a specific message. Initially, I attempted to achieve this using a binding like :style="styles" However, I encountered the following error: The property or method "st ...

Adding a version number to the splash screen in Cordova: A step-by-step guide

After successfully integrating the Cordova Splashscreen plugin into my Ionic project, everything is running smoothly. However, I am now looking to dynamically add a version number to the splash screen without manually editing the Splash Screen PNG file e ...

A guide on utilizing multer-sftp for downloading files

I've been working on this code, but after searching online I still haven't found a way to download a file from the remote server. I can successfully upload files to the server, but downloading them is posing a challenge. var storage = sftpStorag ...

Retrieving the 'red' pixel data from the texture rendered with gl.texImage2D

My objective is to transfer a Float32array to my fragment shader using a texture in order to process the data within the shader and then send it back to JavaScript. Since the data is not in the form of an image, I opted to transmit it as 'gl.R32F&apos ...

Navigate to the following input field upon a keyup event occurring within the table

I have a table that contains multiple input fields in a single row within a td element. I am trying to implement functionality that will automatically shift focus to the next input field when any number is entered. The code works perfectly without the tabl ...

Is there a way to adjust the transparency of individual words in text as you scroll down a page, similar to the effect on https://joincly

Is there a way to achieve a text filling effect on page scroll similar to the one found here: . The specific section reads: "Deepen customer relationships. Own the brand experience. Add high margin revenue. Manage it all in one place. Get back your pr ...

Consolidate HTML project into a unified HTML file

In my current project, I am working with a static HTML report that is organized in the structure outlined below: 1.css 2.font 3.js 4.pages 5.attachments 6.index.html I would like to know how I can combine all these elements to create a unified 'repor ...