DEV Community

Cover image for Vuex: taking user input, adding and removing it from state
Bruno
Bruno

Posted on

Vuex: taking user input, adding and removing it from state

Are you tired of banging your head against the wall trying to manage state in your VueX application? Fear not, because we're here to save the day! In this article, we'll show you how to add and remove items from state with ease, using nothing but some user input and a sprinkle of magic (okay, maybe not magic, but it's still pretty darn simple). Wait! What did you just say? You said ”simple”? 🫒

owl excuse me

Yes, you heard it right! Let's get started and make state management a breeze!πŸ’¨

I'll walk you through the process step by step, but first I'll provide you a resource on VueX in case you're not familiar with how it all fits together. To continue with this step-by-step guide, you will need to have this knowledge.

πŸ“š Vuex

I have previously written an article on Vuex, how it works and how to add it to your project: https://dev.to/bcostaaa01/how-does-vuex-work-and-what-to-use-it-for-4d8k

I encourage you to also go through Vuex's official documentation: https://vuex.vuejs.org/

You should be prepared to go on to the next stages after reading and having a better knowledge of how Vuex and state management in Vue operate.

πŸ‘·β€β™‚οΈ Set up the main component

Create a Vue component that takes user input and two methods that call the addItem and removeItem mutations in the Vuex store where the form is submitted.

Input.vue



<template>
  <div>
    <form @submit.prevent="addItem">
      <input v-model="newItem" placeholder="Add a new item" />
      <button type="submit">Add</button>
    </form>
    <ul>
      <li v-for="(item, index) in items" :key="index">
        {{ item }}
        <button @click="removeItem(index)">Remove</button>
      </li>
    </ul>
  </div>
</template>

<script>
import { mapState } from "vuex";

export default {
  name: "Input",
  data() {
    return {
      newItem: '',
    };
  },
  computed: {
    ...mapState(["items"]),
  },
  methods: {
    addItem() {
        this.$store.dispatch('addItem', this.newItem)
        this.newItem = ''
    },
    removeItem(index) {
        this.$store.dispatch('removeItem', index)
    },
  },
};
</script>


Enter fullscreen mode Exit fullscreen mode
  • the form submits the new item to the items state.
  • the component has a computed property called items that contains the value of the items state.
  • the methods object contains two methods: addItem which dipatches an action which adds a new item to the items state and sets newItem to an empty string, and removeItem, which dispatches an action that removes an item from the items state at the specified index.

πŸ‘₯ Populate the store

Create a Vuex store with an items state, and an addItem and removeItem mutations. Create addItem and removeItem actions that commit the mutations.

index.js



import { createStore } from "vuex";

export default createStore({
  state: {
    items: [],
  },
  mutations: {
    addItem(state, item) {
      state.items.push(item);
    },
    removeItem(state, index) {
      state.items = state.items.filter((_item, i) => i !== index);
    },
  },
  actions: {
    addItem({ commit }, item) {
      commit("addItem", item);
    },
    removeItem({ commit }, index) {
      commit("removeItem", index);
    },
  }
});


Enter fullscreen mode Exit fullscreen mode
  • the addItem mutation adds an item which takes the user input from the form to items.
  • the removeItem mutation removes an item based on the specified index from the items state.

πŸ‘You are now good to go to manage state based on user input! Easy, right? πŸ˜‰

You can find a link to the repo I worked on to showcase this process: https://github.com/bcostaaa01/vuex-user-input - it contains the commits which might also help you better understand the process.

Thank you for reading!πŸ‘‹

I'd like to thank you for reading my article and invite you to follow me on Dev.to, as well as my other platforms:

I look forward to seeing you on my next one!

Until then,
Happy Coding!πŸ‘©β€πŸ’»

Top comments (6)

Collapse
 
gustavupp profile image
Gus Pear 🍐

Well written Bruno. I enjoyed the intro hehe. Keep it up πŸš€πŸŽ―

Collapse
 
bcostaaa01 profile image
Bruno

Thank you very much, Gus!πŸ˜ƒ

Collapse
 
webjose profile image
JosΓ© Pablo RamΓ­rez Vargas

Hmm, for readers out there, a word of caution: Vuex is no longer the official state management package. Pinia is the current offical state management package for Vue.

Collapse
 
bcostaaa01 profile image
Bruno

You are right in part of your statement, but there are still many projects relying on Vuex for state management. It is more a matter of personal preference, in my opinion.

Collapse
 
cliveportman profile image
Clive Portman

As another commenter says, there aren't going to be many instances where anyone can justify using Vuex in a new project. Personal preference could come into it, but probably shouldn't. It'd be interesting to see this article updated with Pinia examples alongside the existing examples perhaps?

Collapse
 
bcostaaa01 profile image
Bruno

There are still many codebases using Vuex for state management. Pinia is not replacing Vuex, in my opinion, but it does have it's advantages (just as Vuex has it's advantages as well), such as being more lightweight. Vuex still has a far bigger community, on the other hand, despite the growth of Pinia, for example.

I am working on an article on Pinia which I will post it very soon, but thank you for your suggestion anyways!