Instead of swapping out the object with a new one, the splice method in Vue.js Vuex simply sets it to undefined

My goal is to update the Vuex state by replacing one object in the state.todos array with another object provided by my component or mutations.

This is how my Vuex state looks like:

`state: {
         todos: [
          {
            title: "First Title",
            desc: [
              {
                name: "First description",
                completed: false,
                editing: false
              }
            ],
            id: 0,
            completed: false,
            show: false
          },
      {
        title: "Second Title",
        desc: [
          {
            name: "Second description",
            completed: false,
            editing: false
          },
          {
            name: "Third Description ",
            editing: false,
            completed: false
          }
        ],
        id: 1,
        completed: false,
        show: false
      }
    ]

Here is the mutation from Vuex that facilitates the change:

finalSaving(state, index, obj) {
  state.todos.splice(index, 1, obj);
}

The component setup looks like this:

<script>
import { mapState, mapMutations } from "vuex";
import deepClone from "clone-deep-js";
export default {
  data() {
    return {
      routeId: this.$route.params.id,
      editObj: { title: "", desc: [], id: null }, 
    };
  },

One specific method in the component causing trouble is:

methods: {
 ...mapMutations(["finalSaving"]),
   finalSave() {
     this.finalSaving(this.routeId, this.editObj);
   },
 },

During mount process, I make sure to clone the relevant object for editing:

 mounted() {
    this.editObj = deepClone(this.todos[this.routeId]);
  },
 computed: {
...mapState(["todos"]),
},

An example of a working mutation in Vuex is as follows:

 agree(state, index) {
  state.todos.splice(index, 1);
},

This Vue component method executes the above mutation properly:

yes(index) {
  this.agree(index);
}

Answer №1

mapMutation methods can only accept a single argument. To pass multiple properties, you can use an object as the argument and then destructure it in the Vuex store.

Update your code like this:

methods: {
 ...mapMutations(["finalSaving"]),
   finalSave() {
     this.finalSaving({routeId: this.routeId, objectToBeEdited: this.editObj});
   },
 },

Next, in the Vuex file:

finalSaving(state, payload) {
  state.todos.splice(payload.routeId, 1, payload.objectToBeEdited);
}

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

Develop a method to streamline the sign-in process for internjs, making it convenient

When starting testing in multiple suites after signing in, I find that my current setup function to instruct the remote to sign in is not very efficient. I am looking to create a helper function that signs in before running each test and can be easily reu ...

Hiding a button based on the visibility of another button in the user's viewport

Is there a way to dynamically hide button B when the user scrolls and button A becomes visible on the screen? Additionally, how can we show button B again once button A is no longer visible to the user? Both buttons should never be visible simultaneously. ...

Implementing Dynamic Checkbox Selection using JavaScript

Could someone please assist me with this coding challenge? HTML <div id="toggle"> <ul> <li class="active"><input type="checkbox" id="test" value="2014" name="test" checked/> 2014</li> <div style="display:block;" id ...

HTML- Any suggestions on how to troubleshoot my sticky navbar not functioning properly?

I'm having trouble creating a sticky navbar. I've attempted to use z-index: 999 but it's not behaving as expected. * { margin: 0; padding: 0; } .navbar { display: flex; align-items: center; justify-items: center; position: ...

concealing additional content within a DIV using ellipsis

Looking to conceal additional text within my DIV element with ellipsis (...) at the end Currently using: <div style="width:200px; height:2em; line-height:2em; overflow:hidden;" id="box"> this is text this is text this is text this is text </div ...

Can multiple if statements be executed simultaneously in plain Javascript? If yes, what is the method to do so?

Currently, I'm developing a game using canvas in HTML, CSS, and vanilla JavaScript. I've successfully created two characters with movement controls assigned to player 1 and player 2. However, a challenge arises when waiting for one player to move ...

Discover the latest version of Vue with the powerful Vuex 4 integration

I'm currently utilizing Vue 3 along with the composition API and I'm exploring the best way to directly map my state from Vuex so that the template can easily access and update it using v-model. Is mapState the solution to this issue, or is ther ...

Component does not detect change when the same number is sent as input

Let me paint you a picture: I have this nifty component, set up with the OnPush strategy, that showcases a PDF document, sliding through pages one by one, and granting users the ability to smoothly glide through pages and jump to specific ones. It even of ...

How can I incorporate multiple states into a conditional statement in ReactJS?

Is there a more efficient way to achieve this task? I'm struggling to come up with a cleaner solution as the current approach looks messy. I need to check multiple states in an if statement and the only method I can think of right now is the one prese ...

Can a JavaScript function be sent back via AJAX from PHP?

Can a javascript function be returned via Ajax from php? Typically, I would just return a value and handle it in plain javascript. However, since I am working on an Apache Cordova mobile app, I need to approach things differently. account = localStorage.g ...

Tips for retrieving the value of a dynamic and multi-update id using jQuery and Ajax

I'm in need of assistance with a few different tasks: Firstly, I am looking to understand how to retrieve the id of an input element when it is dynamically generated from a database. In the HTML, it displays something like field 1 -> id = "pa ...

What is the best way to change an object into a string in node.js?

Recently, I've delved into the world of node js and I'm eager to create a basic coap client and server using this technology. Successfully, I managed to set up a server hosting a text file, but now I aim to access it from the client. var coap = ...

Blockage preventing text entry in a textarea

To enhance the basic formatting capabilities of a textarea, I implemented a solution where a div overlay with the same monospace font and position is used. This approach allows for displaying the text in the div with different colors and boldness. However ...

Tips for making continuous API calls from server-side in Node js/Express js?

I need to continuously call an API from the server side, ensuring it runs 24/7 on a per-second basis. How can I accomplish this task? My attempt in the 'server.js' file is causing an error: 'TypeError: request.put is not a function.' ...

Is the toString() method explicitly invoked by Number() if the value is not of type number or string? (such as a function)

Looking for clarification on the behavior of parseInt() compared to the Number() constructor called as a function. I want to confirm if this is reliable and if there's an official reference to support it. Below is sample code: let adder = (function ...

Issue with WebRTC, socket.io, and node.js: Unable to access the property 'emit' as it is undefined

Currently, I am in the process of creating a webrtc video app. Within the client code section, the following lines are present: getUserMedia(constraints, handlemedia, errorhandle); constraints = {video: true}; function handlemedia(stream){ //other act ...

Discovering the quantity of identical elements within a JavaScript array

Looking for some assistance in solving a JavaScript problem as I am relatively new to the language: I have an array and I need help in determining the count of identical values. Below is my array: var arr = ["red", "blue", "green", "red", "red", "gray"] ...

Sending Node.js FileStream Image to HTML5 FileReader API

Is there a way to utilize Node FileSystem for opening a file and then having it read by the FileReader API? const myFile = "C:\\Users\\Me\\Image.png"; fs.readFile(myFile, (error, data) => { const blob = new B ...

Having trouble getting a local npm installation to work from a specific file path?

After following the instructions from this helpful link to install an npm package through a file path, I encountered an error when attempting to use it: Cannot find module '<module_name>' or its corresponding type declaration Are there an ...

AJAX request returning null value to PHP validator

My current challenge involves sending an email to a PHP script in order to check for availability using ajax and an onKeyUp event in HTML. I've spent hours troubleshooting this issue, trying various approaches, but so far, I have not been able to fin ...