Vuex is exclusively eliminating the initial element

Currently, I have set up the code to remove the activeNote from the array called notes by using the DELETE_NOTE mutation. However, it seems that it only removes the first element of the array.

The content of mutations.js is as follows:

export const mutations = {
  DELETE_NOTE (state) {
    console.log(state.activeNote) // This correctly displays the selected activeNote
    if (typeof state.notes !== 'undefined' && state.notes.length > 0) {
      state.notes.splice(state.activeNote, 1) // This always removes the first element, regardless of the selection
      if (state.notes.length === 0) {
        state.activeNote.text = ''
        state.activeNote.favorite = false
      } else {
        state.activeNote = state.notes[state.notes.length - 1]
      }
    }
  },
  SET_ACTIVE_NOTE (state, note) {
    state.activeNote = note
  }
}

In the actions.js file, we have:

export const actions = {
  deleteNote: ({ commit }) => commit('DELETE_NOTE'),
  updateActiveNote: ({ commit }, note) => commit('SET_ACTIVE_NOTE', note),
}

Furthermore, the getters are defined as:

const getters = {
  activeNote: state => state.activeNote,
  notes: state => state.notes,
}

Last but not least, the component that triggers the mutation looks like this:

<template>
  <div id="toolbar">
    <i @click="deleteNote" class="glyphicon glyphicon-remove"></i>
  </div>
</template>

<script>
import { mapGetters, mapActions } from 'vuex'

export default {
  name: 'toolbar',
  computed: mapGetters([
    'activeNote'
  ]),
  methods: mapActions([
    'deleteNote',
  ])
}
</script>

Answer №1

The usage of the splice method is incorrect. The first argument in the splice method should be the index indicating where to start changing the array. Instead of

state.notes.splice(state.activeNote, 1)

the correct way to use it would be:

 state.notes.splice(state.notes.indexOf(state.activeNote), 1)

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

Tell me the permissions that a user possesses in discord.js

I need help creating a command using Discord.js that can display a user's permissions. For instance, the command could be $permissions @user and it should output something like: "User permissions within this guild: " I'm unsure if ...

Using jQuery to trigger an event when an element is empty or when the element contains children nodes

Is there a way to create a jQuery script that can monitor the children of an element? If the element does not have any children, default scrolling for the entire page is enabled. If the element has children, scrolling for the whole page is disabled. The ...

The functionality of the combobox in Vuetify differs from that of an input field

I have implemented Vuetify and am using its combobox component for search functionality on my website. However, I have noticed that the text value in the combobox only gets added to the watcher when the mouse exits the field. This behavior is not ideal f ...

Defining a TypeScript interface specifically tailored for an object containing arrow functions

I encountered an issue while trying to define an interface for the structure outlined below: interface JSONRecord { [propName: string]: any; } type ReturnType = (id: string|number, field: string, record: JSONRecord) => string export const formatDicti ...

Issues encountered with AngularJS directive binding inner content not functioning as expected

I am currently developing a feature toggle directive, which requires a check to be performed in order to display content if the check is successful. I want the directive to replace itself with its content without creating a new child scope (so I'm try ...

An effective method for retrieving textarea data in Node.js

I am facing an issue where I cannot successfully send data from a <textarea> to Node.js. It seems that the data I'm trying to send is not being received by Node.js. To retrieve data in Node.js: continueBtn.addEventListener("click", ...

What steps can be taken to resolve the error message "t.onSubmit is not a function" that occurs upon form submission?

Upon submitting a form, it should trigger the onSubmit method function. However, an error is being returned instead: TypeError: "t.onSubmit is not a function". I've attempted to address this issue by researching similar problems and solutions provide ...

Guide to fetching and returning data from AJAX using a function

In my JavaScript file, I have a function that retrieves a value asynchronously from the server: function retrieveValue(userId) { $.ajax({ type: "POST", url: "http://localhost/bghitn/web/app_dev.php/get_number_of_articles", data ...

How to Arrange AppBar Elements in Material UI with React

I'm struggling to align the CloseIcon to be at the end of the container using flex-end but I can't seem to locate where to apply that style. import React from 'react'; import { makeStyles, useTheme } from '@material-ui/core/sty ...

Is it possible to trigger an ajaxcall once another one has finished executing?

Just curious, do you think the code snippet below is capable of triggering a second ajax function once the first one has completed successfully? if(xmlHttp) // xmlHttp represents an XMLHttpRequest object { xmlHttp.onreadystatechange = function() ...

Retrieve the content within a div tag

Hey there, I have a div set up as follows: <div>1+1</div> I'm looking to send this '1+1' value over to my javascript code and calculate it to get '2'. Appreciate any help in advance! ...

Update the content on the webpage to display the SQL data generated by selecting options from various dropdown

My database table is structured like this: Name │ Favorite Color │ Age │ Pet ────────┼────────────────┼───────┼─────── Rupert │ Green │ 21 │ ...

Is there a way to redirect using Express JS when the destination is

Hello there, I'm encountering an issue with redirecting in express js. I have a function that should trigger when a submit button is pressed and then redirect to a different page. However, when using res.redirect('/results.ejs');, I receive ...

Discovering the presence of whitespace between rows and columns in a C program

To begin, input two integers representing the height and width of a piece of paper. Then, draw straight lines by first specifying the number of lines and their coordinates. The task is to calculate the number of spaces created by these lines. Here is my ...

Initiate the Html.BeginForm process in an asynchronous manner

Within my ASP.NET MVC 3 application, I am attempting to upload a file using the Html.BeginForm helper, as shown below: <% using (Html.BeginForm("ImportFile", "Home", new { someId = Id }, FormMethod.Post, new { enctype="multipart/form-data" } )) %> ...

Is there a way to access the initial item in a JavaScript array?

Recently, I've been delving into the world of javascript and encountered a task that involves removing the first item from an array. Solution One function getFirst(arr, item) { arr.push(item); var removed = arr.shift(); return removed; } S ...

What is the best way to remove all elements in jQuery?

I need to remove the selected element in my demo using jstree. I have consulted the plugin's API at http://www.jstree.com/api/#/?f=deselect_all([supress_event]), but it seems that it does not deselect the item properly. Here are the steps I have follo ...

Learning the process of utilizing Json in Flot to create visually appealing graphs

I'm currently utilizing the Flot Graph Api to showcase bar charts and line charts on my client-side PHP environment. I am attempting to pass Json data to plot the graph as outlined in their examples. This is how I structure the Json data: [{"label": ...

Group the JSON data in JavaScript by applying a filter

I have a specific json object structure with keys cgi, tag and name, where the cgi key may be repeated in multiple objects. If any cgi has the tag 'revert', then that particular cgi should not be returned. [ { "cgi": "abc-123 ...

Step-by-step guide: Mocking an image using a fixture in Cypress

I'm currently utilizing cypress to run tests on my VueJS application. One issue I am facing involves simulating the display of an image on a page. Specifically, I am trying to load a user profile using the following code snippet: describe('Test ...