Why is it that the .forEach() function has the ability to alter the Vuex state?

After extracting two sets of balances from my vuex state, I decided to merge them into a new array of entries. However, an error is thrown when I try to loop through my copies of the vuex state. Am I missing something?

It seems that the issue lies in the fact that .filter() returns a new array, breaking the connection between coins and the $state.

Even though I am not directly modifying the vuex state, I am still being cautioned against mutating it outside of mutations when dealing with its copies.

Although these assignments may seem like references to the vuex store, they are not (or are they?). I have been trying to figure out what's causing the problem here, but I can't seem to pinpoint it. Any help would be greatly appreciated. Thank you!

filteredItems() {
      let coins = this.$store.state.wallet.balances.filter(( item ) => this.getCoinPropertiesByTicker(item.ticker).staking_available);
      const stakingCoins = this.$store.state.wallet.stakingBalances;
->    coins.forEach((coin) => {     // the error occurs at this point
        const stakingCoin = stakingCoins.user.stats.find((name) => name.ticker === coin.ticker)
        if (stakingCoin) {
          coin.totalAmount = {
            amt: new BigNumber(stakingCoin.balance).decimalPlaces(8).toString(),
            usd: new BigNumber(stakingCoin.balance_usd).decimalPlaces(2).toString()
          }
        }
      return coins
      }



[Vue warn]: Error in callback for watcher "function () { return this._data.$$state }": "Error: [vuex] do not mutate vuex store state outside mutation handlers."

(found in <Root>)


vue.esm.js?a026:1897 Error: [vuex] do not mutate vuex store state outside mutation handlers.
    at assert (vuex.esm.js?2f62:90)
    at Vue.store._vm.$watch.deep (vuex.esm.js?2f62:793)
    at Watcher.run (vue.esm.js?a026:4577)
    at Watcher.update (vue.esm.js?a026:4551)
    at Dep.notify (vue.esm.js?a026:739)
    at Object.reactiveSetter [as amountStaked30] (vue.esm.js?a026:1064)
    at eval (Staking.vue?3a4a:134)
    at Array.forEach (<anonymous>)
    at VueComponent.filteredItems (Staking.vue?3a4a:115)
    at Watcher.get (vue.esm.js?a026:4488)

Answer №1

It has come to my attention, like others have mentioned, that the contents within the array are actually references to the store, even when assigned to a variable.

For my particular scenario, I utilized

JSON.parse(JSON.stringify(this.$store.state.wallet.balances)).filter(( item ) => this.getCoinPropertiesByTicker(item.ticker).staking_available)
, which effectively creates a deep copy and resolves the issue at hand.

Many thanks!

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

Ajax modal login feature refuses to close

Struggling to close a modal login box? Everything seems to be functioning correctly with the modal screen and ajax features, but I'm facing issues when it comes to closing the modal form. The code snippet looks like this: HTML: <a href="#" cla ...

Tips on transforming JSON data into a hierarchical/tree structure with javascript/angularJS

[ {"id":1,"countryname":"India","zoneid":"1","countryid":"1","zonename":"South","stateid":"1","zid":"1","statename":"Karnataka"}, {"id":1,"countryname":"India","zoneid":"1","countryid":"1","zonename":"South","stateid":"2","zid":"1","s ...

Error - Oops! It seems like there was a TypeError that occurred because the property 'innerHTML' cannot be set for something that

I keep encountering this issue in my code. Uncaught TypeError: Cannot set property 'innerHTML' of undefined Despite trying various suggestions from other posts with similar errors like Uncaught TypeError: Cannot set property 'innerHTML&apos ...

Should we pause JQUERY AJAX to prioritize usability, or only when absolutely necessary?

I am struggling with my LoadingStatus Function, which has two options: SHOW and HIDE. When a JQUERY POST is made, the Show option triggers to display, while the HIDE option occurs after the RESPONSE comes back. The problem I'm encountering is that s ...

Troubleshooting a VueJS Problem: Updating $data in the mounted hook

Revision This snippet of Component.vue was extracted from a larger web application where I made a mistake that had significant consequences, all because of a small change I didn't initially notice. An important distinction exists between the followi ...

Angular's innerHTML dilemma

Within my Angular service, I have implemented three methods as shown below: public loadLiveChat() { let url: string; url = this.appConfig.config.liveAgent.liveAgentScriptUrl; this.dynamicallyLoadScript(url); ...

Using a JQuery/AJAX toggle switch to send a POST request to a PHP file without redirecting

I have been experimenting with different methods to achieve a specific functionality, such as using $.ajax in JavaScript and utilizing a jQuery plugin available at this link: http://jquery.malsup.com/form/ I have searched extensively on platforms like Sta ...

The selected jquery script is failing to function as intended

I'm currently implementing jQuery chosen in a select element to enhance user experience, however I'm facing an issue when attempting to copy the chosen div to another div using jQuery $(document).ready(function() { $(".chosen").chosen({}); ...

Starting Web Server using File (file://) protocol

I'm currently using Quasar to develop a Vue SPA web app/page. For this project, the web app will only run by clicking on the index.html file generated by the Quasar packager. This package will not be distributed online or hosted on any domain. My mai ...

Cloning a table row through editing functionality in ReactJS

Hey there, I'm currently working on implementing an edit feature in react.js. The current functionality is such that when the edit button is clicked, it displays the row data in the name and email address fields. If submitted without any changes, it c ...

I'm perplexed by setting up Node.js in order to work with Angular.js

Currently following the Angular tutorial provided at https://docs.angularjs.org/tutorial, but I'm encountering confusion with the Node.js installation. Having already installed node globally on my Mac, the tutorial mentions: The tutorial instructio ...

The option chosen from the ng-options does not remain attached to the drop-down menu

I need some help with AngularJS as I am still getting the hang of it. Take a look at this not-so-pretty page: https://i.sstatic.net/Dtm7j.png This page allows users to add new beers, and each beer can have multiple styles. Clicking 'Add' create ...

React: The received value for the prop type must be a function, but it was an object

I'm stuck trying to make sense of this error message, and my online search has hit a dead end. Any insights would be greatly appreciated! Attention: Prop type validation failed - expected prop type `leoInfo` to be a function from the `prop-types` pack ...

Increase the detection range in empty lists for Vue-draggable-next

I am currently utilizing Vue-draggable-next in conjunction with Vue 3 to enable draggable lists within my application. In certain scenarios, users need to drag items from other lists into lists that are initially empty. I have noticed that the area for det ...

Using the `Array.find()` method in an attempt to dynamically retrieve a specific object value and then return it based on the object name, but unfortunately the function is

I have a collection of objects, each containing its own nested array of objects. My goal is to utilize the Array.find() method to target individual nodes within the array and extract a value from their subarray based on name. Despite having written my fu ...

Implementing an autosuggest feature for the TagsInput component

When developing my website, I utilized JavaScript, the React framework, and a library called mui. One of the user input features on my site is powered by TagsInput, allowing users to input data, press enter, view the tag, and optionally delete it. Unlike ...

capture the emitted value from a child component within a parent component

I am having trouble with a Vue component called vue-datetimepicker. Here is the code for the component: export default { name: 'vue-datetimepicker', data () { return { value: '' } }, watch: { options: functio ...

When the status is set to "Playing," the Discord Audio Player remains silent

So, I'm in the process of updating my Discord audio bot after Discord made changes to their bot API. Despite my best efforts, the bot is not producing any sound. Here's a snippet of the code that is causing trouble: const client = new Discord.Cl ...

Is there a way for me to retrieve SCSS color variables within the javascript of a Vue template?

I have a unique challenge in my application involving a component called Notification. To bring notifications to other components, I utilize the mixin method toast('message to display', 'color-variable'). My goal is to set the backgroun ...

Ways to retrieve nested data from an object

I have added an object with categories in a database. It displays the price and date of addition. How can I output the date to the console? Currently, in the console, it shows: [ [ { cost: '50$', date: [Object] } ] ]. I need to extract the inform ...