Error is caused by state variable triggering mutation

In my store module, I am encountering an issue with the following pseudo-code:

const state = {
  users: []
}

const actions = {
 addUsers: async ({commit, state}, payload) => {
   let users = state.users // <-- problem
   // fetching new users
   for(let i of newUsersThatGotFetched) {
     users.push('user1') // <-- really slow
   }
   commit('setUsers',users)
 }
}

const mutations = {
  setUsers: (state, { users }) => {
    Vue.set(state, 'users', users)
   }
  }

Upon running this code, I am getting the error message

Error: [vuex] Do not mutate vuex store state outside mutation handlers
.

Disabling strict mode resolves the error, but results in a significant decrease in performance. It seems like the errors are occurring without being displayed.

The issue appears to be at the point where I commented // <-- problem. However, when I modify that line to

 let users = []

everything functions smoothly. Unfortunately, I require the data from state.users and cannot proceed with an empty array.

Answer №1

The issue lies with the line users.push('user1'), as it directly modifies the state.

To address this, refrain from making any direct changes to the state in actions and instead handle these mutations within a separate mutation function.

 addUsers: async ({ commit }, payload) => {
   // fetching new users
   commit('setUsers', newUsersThatGotFetched)
 }

In the mutation function, incorporate the logic to add the new users to the state.

const mutations = {
  setUsers: (state, users) => {
    state.users.concat(users);
    // or apply custom logic for adding users
    users.forEach(user => {
      if (whatever) state.users.push(user)
    });
  }
}

The lagging performance can be attributed to Strict mode

Strict mode executes a synchronous deep watcher on the state tree to detect inappropriate mutations, resulting in increased overhead when multiple state modifications are made. It is advisable to disable it in production to enhance performance efficiency.

To optimize the mutation process, consider making changes on a new array before replacing the existing one in the state.

const mutations = {
  setUsers: (state, newUsers) => {
    state.users = newUsers.reduce((users, user) => {
      if (whatever) users.push(user);
      return users;
    }, state.users.slice()); // here, we initiate with a copy of the array
  }
}

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

I am looking to generate an array containing sub arrays so that I can easily iterate through the JSON data

I'm relatively new to creating subarrays and PHP, so please bear with me. I have some code that generates a JSON array, which is shown below. foreach ($result as $row) { $points = $row['points']; $price = ...

What is the best way to bring a module into an Angular project?

I have a project in Angular with an additional module created as an npm package. The structure of the module is as follows: --otherModule --other-module.module.ts --index.ts --package.json index.ts: export { OtherModule } from './other-module ...

Starting your React application with the `npm start` command

After creating my react app using the create-react-app command, I named it react-app. These were the steps I followed: Navigate to the directory by typing cd react-app/ Run the command npm start Encountered an error message that reads; npm ERR! Missing ...

Why isn't the correct component being shown by react-router?

I have encountered an issue with my code. When I type localhost:8080 in the browser, it displays the App.js component as expected. However, upon navigating to localhost:8080/#/hello, it still shows the App.js component instead of hello.js. Interestingly, ...

SimpleLightBox refuses to function

Having trouble getting SimpleLightBox to work properly? It seems like when you click on an image, it opens as a regular image on a blank page. I've added the JS and CSS files correctly (I double-checked in the source code) and included the HTML and JS ...

What could be causing my Leaflet popup to suddenly close?

My feature allows users to search for a marker and zoom to its location, triggering the popup to open. Everything is functioning correctly, except that the popup closes after the function executes. I am struggling to pinpoint what is causing the popup to c ...

In Certain Circumstances, Redirects Are Applicable

I have set up Private Routing in my project. With this configuration, if there is a token stored in the localStorage, users can access private routes. If not, they will be redirected to the /404 page: const token = localStorage.getItem('token'); ...

What are the steps to configure an option date for Yesterday, Today, and Tomorrow?

I have been working on setting options for dates like yesterday, today, and tomorrow. I have implemented the following code which is functioning properly, but it is not displaying yesterday's date. I want today's date to be selected and also disp ...

The navigation bar initially fills the width of the screen, but does not adjust to match the width of the table when scrolling

I've spent the last 2 hours playing around with CSS, using width:100% and width:100vw, but nothing seems to be working. Currently, the navigation bar fits perfectly across the screen on desktop browsers, so there doesn't seem to be an issue ther ...

Display PDF file retrieved from the server using javascript

I am currently working on a web application using JavaScript, jQuery, and Node.js. I need to receive a PDF file from the server and display it in a new browser window. While I believe I have successfully received the file on the client side (the window sh ...

JS - What is causing my JavaScript src to not work properly?

Here is a snippet of my code: <form name="calculator"> <input type="button" name="latest" value="You are not using the latest version."> <script src="http://www.alvinneo.com/bulbuleatsfood.js"> if(latest-version==="1.0.4.2"){ document.ca ...

Display the message "currently being loaded" on a Django platform

I'm a newcomer to django and styling and I have two things I want to address. First, I have an algorithm running on the upload file that takes time to load. I want to display a loading message until the output.csv file is generated and ready for downl ...

Creating a "select all" feature in an HTML multiple select box with jQuery - a step-by-step guide

I'm currently working on an HTML form that includes a multiple select box. I am looking to create a "select all" option within the multiple select box so that when a user clicks on that option, all other options in the select box are automatically sel ...

Simulate a failed axios get request resulting in an undefined response

I'm having an issue with my Jest test mock for an axios get request, as it's returning undefined as the response. I'm not sure where I might be going wrong? Here is the component with the axios call: import {AgGridReact} from "ag-grid- ...

Attempting to configure a discord bot. Can anyone help me identify the issue?

I've been working on setting up a discord bot using Discord.js. I have all the necessary tools installed - Node.js, Discord.js, and Visual Studio Code. I've even created an application and obtained a token for my bot. However, I'm running in ...

The controller is providing a null response following an ajax Post request

I am having trouble with my ajax Post request targeting the edit action method in my controller. The issue is that none of the values are being populated, they all come back as null. What should be happening is that when the '.save-user' button ...

Using AngularJS to access JSON files through the $http service

I'm experiencing difficulties reading data from my test.json file using the #http service. I have everything set up on a xampp localhost, but I can't seem to figure out what's going wrong. Here's the JavaScript code. Thank you in advanc ...

Creating a search bar with React-Redux: A step-by-step guide

Hey everyone, I've got this component here: const Iphone = ({phones,searchQuery}) => { const filterIphone = phones.map((p, index) => (<div className="model" key={index}> <NavLink to={'/p/' + p.id}>{p.body.mod ...

Releasing Typescript 2.3 Modules on NPM for Integration with Angular 4

Although there are instructions available in Writing NPM modules in Typescript, they are outdated and there are numerous conflicting answers that may not be suitable for Angular. Additionally, Jason Aden has delivered an informative presentation on youtu ...

How to utilize a parameter value as the name of an array in Jquery

I am encountering an issue with the following lines of code: $(document).ready(function () { getJsonDataToSelect("ajax/json/assi.hotel.json", '#assi_hotel', 'hotelName'); }); function getJsonDataToSelect(url, id, key){ ...