How can VueX be leveraged to add an item to an array and also delete an item from the same array?

https://stackblitz.com/edit/vue-script-setup-with-vuex-gfjaff?file=src/components/UserProfile.vue

I'm currently working on a feature where I can input a name into a dispatch function and have it added to an array. Eventually, I plan to include a text input field for this purpose but for now, I'm taking baby steps.

After adding names to the array, I want to be able to click on a delete button next to each name to remove it. However, I seem to be facing some challenges when trying to implement "event.target.value". This seems to be causing issues in my code.

Can someone help me identify what's not right in the code? What part am I missing or getting wrong?

store.js

import { createStore } from 'vuex'

export default createStore({
  state: () => ({
    list: ['bob', 'joe', 'harry'],
  }),
  getters: {
    listStatus: (state) => state.list,
  },
  actions: {
    addName({ commit }, { name }) {
      commit('ADD_NAME', name)
    },
    removeName({commit}, {name}) {
      commit('REMOVE-NAME', name)
    }
  },
  mutations: {
    ADD_NAME(state, name) {
      state.list.push(name)
    },
    REMOVE_NAME(state, event_target_name){
      state.list.filter(element => element !== event_target_name)
    }
  },
})

userList.vue

<template>
  <div v-for="name in listStatus">
    <li>{{ name }}</li>
    <button @click="removeName(event.target.value)">Remove</button>
  </div>
  <button @click="addName">ADD NAME</button>
</template>

<script setup>
import { computed } from 'vue'
import { useStore } from 'vuex'

const store = useStore()
const listStatus = computed(() => store.getters.listStatus)
// const addName = (input_name) => store.dispatch('addName', { name: input_name }) --------- DOESN'T WORK
const addName = () => store.dispatch('addName', { name: 'tommy' })
const removeName = (event) => store.dispatch('remove-name', { name: event.target.value })
</script>

Answer №1

To access the event within an inline handler, you can use $event.

<button @click="deleteItem($event.target.value)">

Answer №2

According to the information provided in the guidelines:

In inline event handlers, a method handler will automatically receive the native DOM Event object that triggers it.

In this specific scenario, when the remove button activates the removeName method, the event will be received automatically, so there is no need to explicitly pass it unless it's the only parameter being passed.

However, there are two issues in your code:

  1. You are passing event, but you should use $event, a special variable. If you want to pass event, then utilize arrow function syntax. For more details, check this resource.
  2. Even if removeName(event.target.value) works, it means you are already passing the target value. Therefore, inside the method, access it as removeName(target_value), not removeName(event). By following this approach, you won't be attempting to access a value from the value itself.

To address these concerns and ensure correct functionality, make the following adjustments to your code:

Within the template-

 <button @click="removeName">Remove</button>

In JavaScript (using the same logic)-

const removeName = (event) => store.dispatch('remove-name', { name: event.target.value })

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

Troubleshooting issue with Express.json() functionality in the latest release of version 4.17

I'm currently exploring the MEAN stack and I am focused on performing CRUD operations. However, when I send data in the request body from Angular to the server, I end up receiving an empty request body. I'm unsure of where I might be making a mis ...

Issue encountered while utilizing JQueryUI alongside TypeScript and the definition file from DefinitelyTyped

Currently, I'm attempting to incorporate JQueryUI with TypeScript by first installing JQueryUI using npm install jquery-ui-dist, and then installing JQuery with npm install jquery. Additionally, I have included the definition files from DefinitelyType ...

Automatically fill in the Modal popup

Today, I encountered a challenge while trying to keep the current page in a jQuery data table. Clicking on the "Edit" link in a row would open a modal pop-up and fill in the controls. However, this action resulted in a postback that set the page back to pa ...

Make sure to choose the radio button that corresponds to the desired title value, as this will be automatically added to the input text

Visit this link for a live example. <div class='liveExample'> <input type="radio" name="gender" value="Mr." checked>Mr. <input type="radio" name="gender" value="Mrs.">Mrs. <p>First name: <input data-bind=&ap ...

Retrieve information from various tables in a SQLite database using Node.js

Is there a method to retrieve all data from multiple tables in a database? Currently, I have managed to fetch all data from a single table: router.get('/', function (req, res, next) { db.serialize(function () { db.all('SELECT id, name ...

Tips for updating parameters that are defined in a controller within a promise

Currently, I am developing a single page application using Angular and TypeScript. I am facing an issue with updating the parameter value (_isShowFirst) of the controller inside a promise function. It seems like nothing is recognized within the promise blo ...

Live monitor database changes with AJAX and SQL technology

Is there a way to implement real-time updating of user ratings on comments in an application with a connected database? I've explored various sources but the responses have been inconsistent and inconclusive. I am currently creating an app where user ...

Executing a request via ajax using a radio button

Here is the input that I am working with: <input id="offline-42" onclick="javascript:checkoutSwitch(false);controlDivPayment('42');" name="payment" type="radio" value="offline-42" /> I am attempting to use ajax to add a product to the sh ...

Create a line break in an alert using PHP

<?php function alert($msg) { echo "<script type='text/javascript'>alert('$msg');</script>"; } if(array_key_exists('btnRegisterAdmins', $_POST)) { $fname = $_POST['FirstName']; $lname=$_POST['La ...

Exploring Next.js Font Styling and Utilizing CSS Variables

I'm attempting to implement the "next" method for adding fonts, but I find the process described quite complex just to preload a font. I experimented with exporting a function to create the font and then using a variable tag to generate a CSS variabl ...

Unable to properly access required file path through HTML source

I have a confidential folder named 'inc' where I store sensitive files such as passwords in php connection files. This folder is located at the same level as the 'public_html' folder. I successfully accessed php files with database conn ...

Trouble with Loading Google Place Autocomplete API in HTML

I utilized the Google MAP Place Autocomplete API for a web project. Click here to view the code and output. <form> <input id="origin-input" type="text" class="form-control" placeholder="From"/> <br/> <input id="de ...

What is the best way to display a jQuery UI dialog when the page is reloaded?

I am trying to display a jQuery UI dialog when the user tries to reload or close the browser. Here is my code snippet: $(window).bind('beforeunload', function () { $("#confirm").dialog({ width: 500, modal: true, buttons: { ...

Issues arise when trying to integrate external JavaScript files into a Vue application

I am facing an issue with including external JS files in my HTML document. The website requires these files to function properly. What I have attempted: In the main.js file, I tried adding these imports: import '../../assets/js/jquery-3.5.1.min&apos ...

Storing data in the browser's LocalStorage after a Vue3 component has

Whenever a user successfully logs into the application, a nav bar is supposed to load user data. However, there seems to be a timing issue with localStorage being set slightly after the nav bar is loaded. Using a setTimeout() function resolves the issue, b ...

Is the shift key being pressed during the onClick event in React?

To trigger an onClick event only when the meta(mac) / ctrl(win) key is pressed, follow these steps: This is what I attempted: const [shiftOn, setShiftOn] = useState(false) useEffect(() => { document.addEventListener('keydown', (e) => ...

What is the purpose of returning a function in a React Hook?

Currently, I am incorporating Material-UI components into my project and have implemented the AutoComplete component in my application. While exploring an example provided by the Material-UI team, I stumbled upon a fascinating instance of using Ajax data ...

Loop through and write files using Node.js

I've been experimenting with a Google Trends API integration in node.js to gather data on the popularity of various search terms. My goal is to store a list of search words in an array, iterate through this array, call the Google Trends API for each ...

Can Node.js endpoints effectively handle the garbage collection of new class instances?

Just diving into node.js I'm currently dealing with a lengthy and messy function that constructs a CYPHER query for Neo4j. I am considering transforming it into a class, complete with methods, along with a corresponding mocha spec. The expected usag ...

Is it possible to dynamically add and remove items using React state?

I am currently working on implementing a dynamic queue of game players in my React state. The goal is to avoid hardcoding the number of players who can participate and achieve this state update using a JS FIFO queue. My objective is to create a player que ...