What causes the imported constant in Vue to fluctuate in value?

In my Vue component, I am importing an array named CHART_CARDS. This array is used to set the initial state for another array called chartCards, which can be modified by the user.

import { CHART_CARDS } from '~/constants/chartCards'

...

export default {
  data(){
    return {
      chartCards: []
    }
  },
  async created(){
    if (this.$auth.user.settings && this.$auth.user.settings.length) {
      this.chartCards = this.$auth.user.settings
    } else {
      this.chartCards = CHART_CARDS
    }
  }
}

Essentially, the `chartCards` data property can either take its value from the imported array or from a predefined database table.

The issue arises when I try to reset the `chartCards` variable using a method called reset:

     async reset () {
         console.log('going to reset.  CHART_CARDS looks like:')
         console.log(CHART_CARDS)
         this.chartCards = CHART_CARDS
         await this.updateCards()
         console.log('chart cards after updating:')
         console.log(this.chartCards)
     }

Strangely, updating `chartCards` also seems to affect the values in `CHART_CARDS`. Despite no other parts of the code altering `CHART_CARDS`, both console logs display the same updated array. Why is the value of `CHART_CARDS` changing unexpectedly?

Answer №1

It has been noted in the feedback that the CHART_CARDS array likely contains objects, and it is probable that these objects are being modified somewhere within your code.

There is a simple solution to this issue with some slight adjustments to the API.

~/constants/chartCards.js

export function getChartCards () {
  return [
    {...},
    {...},
    ...
  ]
}

App.vue

import { getChartCards } from '~/constants/chartCards'

...

export default {
  data(){
    return {
      chartCards: []
    }
  },
  async created(){
    if (this.$auth.user.settings && this.$auth.user.settings.length) {
      this.chartCards = this.$auth.user.settings
    } else {
      this.chartCards = getChartCards()
    }
  }
}

By always generating a new array containing distinct objects, any changes made to one instance of chartCards will not affect another.

If you absolutely insist on sticking with your current API, it is possible to achieve that as well. You just need to create a deep copy of your CHART_CARDS object before assigning it.

import { CHART_CARDS } from '~/constants/chartCards'

...

export default {
  data(){
    return {
      chartCards: []
    }
  },
  async created(){
    if (this.$auth.user.settings && this.$auth.user.settings.length) {
      this.chartCards = this.$auth.user.settings
    } else {
      this.chartCards = JSON.parse(JSON.stringify(CHART_CARDS)) // This will not work if your CHART_CARDS has methods
    }
  }
}

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

Tips on emphasizing all div elements and incorporating navigation to each of them

I am seeking a method to enhance a div with highlighting when there is a click or mouseover event. For instance, changing or adding a border color using JavaScript on click or mouseover is straightforward. Recently, I have been contemplating the idea of a ...

Clear the local storage once the URL's view has been fully loaded

When retrieving details of a specific item by passing URL parameters stored in local storage, I encountered an issue. I need to delete the local storage variables after the view is loaded. However, what actually happens is that the local storage variable ...

Error encountered when using Vue's conditional rendering in conjunction with conditional statements

Currently, I am in the process of learning Vue and facing some challenges with conditional rendering. Although it is not causing any disruptions to the app's functionality, I keep encountering a console error. At the beginning, the character object i ...

Implementing a file download feature in Python when clicking on a hyperlink

I'm attempting to click on the href link below. href="javascript:;" <div class="xlsdownload"> <a id="downloadOCTable" download="data-download.csv" href="javascript:;" onclick=&q ...

Looking for a Communication Manager specifically designed for Vue components?

While working on a Vue.js project, I found myself creating and utilizing numerous components. But soon enough, I encountered the challenge of managing multiple eventemitters and props. To better illustrate this issue, let's consider an example scenar ...

TypeScript React Object.assign method return type

I have a unique custom function that utilizes Object.assign to return a specific result. The documentation mentions that this function returns an array, but surprisingly, it can be destructured both as an array and an object. Check out the code snippet be ...

Unable to store loop information fetched from api into a JSON file

I'm currently facing an issue with my code where I am trying to save the results from looping through an API into a JSON file using writeFileSync. Here is the code snippet in question: function processRarity(limit) { var resultJson = []; for ( ...

The Vue-Apollo V4 composition API from @vue/apollo-composable encountered an error while trying to call it on the login form, resulting in the issue TS2349: "This expression is not callable. Type 'Ref<any>' has no

Being a newcomer in the world of Apollo, I am utilizing Vue composition API along with @vue/apollo-composable version V4 for my vue apollo client. My backend consists of a nodejs server with apollo server. Currently, I am facing an issue on the login page ...

Are node.js and AngularJS connected in any way?

Node.js relies on npm for package management, while AngularJS CLI also uses npm for its modules. Is there a connection between these two? I have installed Node.js and tested it with a simple 'hello.js' file containing just one line of code: con ...

Inject SCSS variables into Typescript in Vue 2 Using Vue-cli 5

When working on my Vue 2 project (created using the Vue-cli v4), I successfully imported variables from my SCSS file into my typescript (.vue files) without any issues. I had the :export { ... } in my SCSS file _variables.scss, along with shims.scss.d.ts ...

Tips for overlaying an image on a div regardless of its height

(!) Although this question may seem repetitive, I have not been able to find a suitable solution in any of the previous 10 topics. I apologize for the inconvenience and am actively seeking a resolution to this unique situation; Allow me to outline the iss ...

JQuery form plugin - submitting a form automatically on onchange event

As a beginner in JQuery, I am looking to utilize the JQuery form plugin for file uploads and would like to trigger the form submission as soon as a file is selected. This should occur upon the onchange event of the input tag: myfile. <html> <body ...

Failure to trigger an event in Vue.js

I've implemented an overlay feature for my modal that should toggle the modal when clicked. Here's the code snippet I have in my mounted() method: const overlay = document.querySelector(".modal-overlay"); overlay.addEventListener("click", this ...

The CSS hamburger menu halves in size when being closed

I have successfully created a CSS/JS hamburger menu with a transforming icon upon clicking. However, I encountered a bug where, upon clicking the 'close' button on the hamburger, the navigation menu cuts behind the header, resulting in a messy ap ...

jQuery ajaxSetup: handling error retries for ajax calls is not possible

When using $.ajaxSetup(), I am faced with the challenge of making an AJAX request after refreshing a valid token in case the previous token has expired. The issue arises when attempting to execute $.ajax(this) within the error callback. $.ajax({ url: ...

The system encountered an error when attempting to convert the data '19-10-2002' into a date format

I am trying to pass a date parameter in the format (dd-MM-yyyy) and then convert it into the format (yyyy-MM-dd) before sending it via API. Here is my code: convert(date:string){ date //is in the format(dd-MM-yyyy) date = formatDate(date , " ...

I am encountering a problem with my Vuex getter where it is sending an Array with a length of 0, but when expanded in the console,

Currently, I'm utilizing Vuex to interact with a Django API in order to fetch count data. state: { DailyCycleDate: [] }, getters: { DailyCycleDate : state => { console.log('Getter') console.log('Length of Array: &apo ...

What is the reason behind Meteor automatically updating a record without the need to run a "Meteor.call" function for an update?

I am currently developing a Meteor.js application and while I have grasped the basic concepts of Meteor, I feel like I might be missing something when it comes to its reactivity principles. Using angular-meteor, I am utilizing a $scope variable in my view ...

The JSON.parse function encounters issues when trying to parse due to a SyntaxError: Unexpected character found after JSON at position 2, causing it to be unable

I've encountered an issue with my JavaScript code when trying to retrieve the value of the details field from JSON data. While all other values are successfully passed to their respective fields, the details field generates the following error: "Unabl ...

What is the best way to bundle a node module with the choice of adding submodules?

I am in the process of developing a JavaScript library that consists of a central core module and multiple optional submodules that enhance the functionalities of the core module. This library is specifically designed for the browser environment, utilizing ...