Tips for modifying a state array in Vuex

I have the ability to add and remove entries, but I'm struggling with editing. How can I achieve this using VUEJS, VUEX, and JavaScript?

For adding entries, I know I should use PUSH, and for removing entries, SPLICE works fine. But what about editing?

Below is an example of my current implementation:

<b-button type="submit" @click.prevent="submit()">SAVE</b-button>

methods: {      
  submit() {
    this.$v.edit_category.$touch();
    if(this.$v.edit_category.$error) return
    this.editCategory()
  },
  editCategory() {
    const category = {
      value: this.edit_category.value,
      text: this.edit_category.text,
      category_active: this.edit_category.category_active,
    }        
    
    this.$store.commit('saveCategory', category)
  },
},

In my store.js file:

actions: {
addCategory({ commit }, payload) {
  console.log(payload)
  commit('addCategory', payload) 
},
saveCategory({ commit }, payload) {
  console.log(payload)
  commit('saveCategory', payload) 
},
 deleteCategory({ commit }, payload) {
  console.log(payload)
  commit('deleteCategory', payload) 
}


mutations: {
addCategory(state, category) {   
  state.categories.push(category)      
},
saveCategory(state, payload) {
  state.categories.push(payload)
},
deleteCategory(state, category) {
  var index = state.categories.findIndex(c => c.value === category.value)
  state.categories.splice(index, 1)
},

Answer №1

Utilize Vue.set:

import Vue from 'vue';
// ...

editCategory(state, category) {
  var index = state.categories.findIndex(c => c.value === category.value);
  Vue.set(state.categories, index, category);  // ✅ Vue.set
},

This is essential because according to the information provided in the documentation:

Vue cannot recognize the following modifications made to an array:

When you directly assign a new value to an item using its index, for example, vm.items[indexOfItem] = 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

Apexcharts - Blank space in area chart

I am currently facing an issue while trying to create an area chart using apexcharts on nuxt (vue2). The problem is that the area is not being filled as expected, and the options I have set in chartOptions for fill are affecting the line itself instead of ...

What is causing the Firebase emulator to crash when I run my Express code?

This project is utilizing express.js along with firebase. Whenever attempting to access a different file containing routes, it results in failure. Instead of successful emulation, an error is thrown when running this code: const functions = require(" ...

In Vue JS, what is the best way to access my data within a filter function written in Javascript?

One feature I added to our application is a validation check for each row to ensure there are no duplicate column values. While the validation works fine, I'm encountering an issue with deleting rows. For example: https://i.stack.imgur.com/NylYj.png ...

The vue-router in Vue 3 is encountering an issue with the "createWebHistory" function, as it could not

I recently upgraded my Laravel 8 project to use Laravel Mix v6 in order to support Vue 3. However, I encountered an issue with the createWebHistory method from vue-router 4. In my package.json file: { "private": true, "scripts" ...

Repetitive cycling through an array

My array consists of classes: const transferClasses = [ { id: "c5d91430-aaab-ed11-8daf-85953743f5cc", name: "Class1", isTransfer: false, children: [], }, { id: "775cb75d-aaab-ed11-8daf-85953743f5cc", ...

The domain name or IP address does not correspond to the alternate names listed on the certificate

I am currently facing an issue with installing npm packages in my react native project. Every attempt to install a package from npm results in the error message shown below: fitz:tesseractOcrSample fitzmode$ npm i npm ERR! request to https://registry.npmj ...

The constructor error in ng-serve signalizes an issue in

Currently, I am developing an AngularJS application. However, when attempting to start the dev server, I encountered an issue with my ng serve command: https://i.stack.imgur.com/QujSe.png ...

What is the best way to bring up the keyboard on an iPhone when focusing an HTML text field?

Currently working on developing a web app for iPhone, and looking to implement a feature where a text field is automatically focused upon page load, prompting the keyboard to appear. Despite attempting the standard Javascript method: input.focus(); I see ...

The partition.nodes(root) function in d3.js does not assign values to the x or dx properties of the nodes

I am currently experimenting with d3.js to create a unique icicle tree visualization using data sourced from a .json file. The challenge I'm facing lies in the fact that the x and dx attributes of the partition nodes are consistently being set to 0. M ...

Switch the image displayed on hover over an image using the #map attribute

Recently, I successfully integrated a database connection into this website and made it dynamic. The overall design of the site was already in place, so my main focus was on adding the functionality of the database connection. However, after implementing ...

The error message states that there is a problem with the function task.dueDate.toDate,

I am currently utilizing Firebase as my database along with Next.js. I have encountered an issue when trying to read data from Firebase, specifically related to the due date field, which is of timestamp datatype. Here is the code snippet where I attempt to ...

Error occurs despite successful 200 response from Ajax delete request

I've been working on setting up a simple API for my project and encountered an issue. When I send a DELETE request using jQuery Ajax, the request goes through successfully, deletes the specified entry in the database, returns a status of 200, but trig ...

Exploring MongoDB through proxyquire

To simulate a MongoDB dependency using proxyquire in my testing scenario, I have the following code snippet: var proxyquire = require('proxyquire'); var controller = path.resolve('.path/to/controller/file.js'); inside the before each ...

Error-free ngClick doesn't trigger AngularJS controller method

I am struggling to trigger the removePlayer(playerId) method upon clicking a button. However, it seems that the method is not being called, as I have placed a console.log() statement at the top and the console remains empty. This situation has left me puz ...

Why does Vue continuously insert undefined values when adding non-consecutive indexes to an array?

In my application, users can select values from a dropdown list and add them to an array by clicking the "add" button. The goal is to use the selected value's id as the index in the array. For example: List of Values 1 - Apple 3 - Bananas 8 - P ...

Attempting to obtain a score value from the input, but unsuccessful in doing so

Prior to posing this question, I had already managed to successfully retrieve the score value. Below is my original script: <script> $.ajax({ type: "POST", url: "https://example.com/paylist.php?acc=useraccount&json=1", ...

"Troubleshooting Problems with Scaling in the jQuery Mouse Wheel Plugin

I am currently utilizing this code in conjunction with the following plugin: mouse wheel $('#painter').on('mousewheel', function(e) { cp.scale(2, 2); var e0 = e.originalEvent, delta = e0.wheelDelta || -e0.de ...

What steps should be followed to execute this moment.js code in an Angular.js controller using Node.js?

I am trying to adapt the following node.js code that uses moment.js into an AngularJS controller: var myDate = new Date("2008-01-01"); myDate.setMonth(myDate.getMonth() + 13); var answer = moment(myDate).format('YYYY-MM-DD'); To achieve this, I ...

Encountering a Node.js error while using ssh2: ECONNRESET read error

I have been attempting to utilize npm's ssh2 package to establish an SSH connection and remotely access a machine. The code functions properly for connections from Windows to Linux/MacOS, but encounters issues when connecting from Windows to Windows ( ...

Display items in a not predetermined order

Despite its simplicity, I am struggling to get this working. My aim is to create a quiz program using JavaScript. Here is the basic structure: <ul> <li>option1</li> <li>option2</li> <li>option3</li> </ul> &l ...