Navigate back to the homepage
BLOG
Try NowLogin
Back

Vuex: State management for Vue Projects

Samaila Bala
March 10th, 2021 · 6 min read

State is a crucial part of Vue applications and other frontend frameworks as it is responsible for how data is passed among components and views. The managing of state tends to become complex as an application grows larger. In this article, we will look at how to use a popular state management library of Vue called Vuex to manage state in Vue projects. But before we talk about State management we have to backtrack a little bit and talk about state.

What is State?

Components in a Vue application contain data that may be dynamic and likely to change across the lifecycle of the component. A state is basically an object where the data a component needs is stored. For example, we can store a message a component needs in the state and display the message whenever the component is rendered. In Vue components, the state is stored in the data function so that each instance can maintain a copy of its state. The example below shows how to create a state for a single file component

1<template>
2 <button>{{message}}</button>
3</template>
4
5<script>
6export default(){
7 data(){
8 message: 'Hello world'
9 }
10}
11</script>

What is State Management?

State management is a way of managing the state across multiple UI components efficiently. As we discussed earlier when an application becomes complex so does managing its state due to shared data across many components that need to interact with each other. This unique problem has giving rise to state management libraries in the last few years.

State management libraries provide a solution to this problem by providing a centralized store for storing state that can be used across components even if the components are unrelated. As opposed to passing props down the tree, which can become really complex for deeply nested components. Some popular state management libraries for Vue are: Vuex, Redux, Mobx, and vue-stash.

What is Vuex?

Vuex is a state management library and state management pattern geared towards Vue applications. It makes managing state in Vue applications easier by providing a central storage for the state (and other computations) called a store. That way you can keep that business logic away from your components. Vuex is inspired by other state management libraries like Flux and Redux which advocate for the separation of a shared state, the major difference between Vuex and these libraries is Vuex is geared more towards the reactive system of Vue.js

Why Vuex?

As mentioned earlier there are other state management libraries for Vue like Redux, so why should you use Vuex?

  • Easier learning curve when compared to other state management libraries: since Vuex was made with Vue in mind it makes it easier integrating it into a Vue application, you can also quickstart a Vuex application from the vue-cli.
  • Mutations: In Vuex state isn’t immutable because Vuex provides designated functions called mutations for modifying state without entirely replacing it.
  • Easy to use dev tools: The Vue Dev Tools can also be used for Vuex applications making it easier to track state changes and also debug Vuex applications.

Getting Started

I will be demonstrating practically how to use Vuex to manage state in a Vue application by building a to do list. Open your terminal and run the code below to install vue-cli

1npm install -g @vue/cli
2# OR
3yarn global add @vue/cli

The vue-cli is a standard tooling for Vue.js development. After installing the CLI run the code below to initialize a new Vue project

1vue create vuex-tutorial

After initializing a Vue project, navigate to the project directory

1cd vuex-tutorial

Run the command below to install Vuex

1npm install vuex --save
2# OR
3yarn add vuex

After installation run the code below to start the application

1npm run serve
2# OR
3yarn serve

Lastly, this is an optional step but very recommended: vue-devtools is a browser plugin that makes it easier to debug Vue.js applications, head over here to download and install the extension compatible for your browser.

Creating Components

Before we go ahead into integrating Vuex into our application let’s create the components we will be needing for the application.

Go to the components directory and delete HelloWorld.vue as we won’t be needing it for our application. Create a file called TodoList.vue in the components directory, open the file and paste the code below

1<template>
2 <div class="todo-list">
3 <div class="todo-item" v-for="todo in todos" :key="todo.id">
4 <p>{{ todo.title }}</p>
5 <input
6 type="checkbox"
7 name="todo.id"
8 v-on:change="updateTodo(todo)"
9 v-bind:checked="todo.completed"
10 />
11 </div>
12 <p>Completed Todos: {{ todosCount }}</p>
13 </div>
14</template>
15
16<script>
17export default {
18 data: () => {
19 return {
20 todos: [],
21 };
22 },
23};
24</script>

This component will contain the list of Todos for the application. Create another file called TodoForm.vue in the components directory and paste the code below

1<template>
2 <form class="todo-form" @submit="submitTodo">
3 <input
4 class="todo-input"
5 name="todo"
6 v-model="todo"
7 placeholder="Start typing..."
8 required
9 />
10 <button class="todo-btn" type="submit">Add Todo</button>
11 </form>
12</template>
13
14<script>
15export default {
16 data() {
17 return {
18 todo: '',
19 };
20 },
21 methods: {
22 submitTodo: function(event) {
23 event.preventDefault();
24 console.log(Todo)
25 },
26 },
27};
28</script>

This contains a form to add a new note to the note list. Go to App.vue and replace the contents with the code below

1<template>
2 <div id="app" class="container">
3 <h1>todos...</h1>
4 <TodoForm />
5 <TodoList />
6 </div>
7</template>
8<script>
9import TodoList from './components/TodoList';
10import TodoForm from './components/TodoForm';
11export default {
12 name: 'App',
13 components: {
14 TodoList,
15 TodoForm,
16 },
17};
18</script>

Creating a Vuex Store

A store is the single source of truth in a Vuex application and is responsible for holding the state of all the components in the application. Navigate to the src directory of the application and create a store.js file. Open the file and paste the code below

1import Vue from 'vue';
2import Vuex from 'vuex';
3Vue.use(Vuex);
4export const store = new Vuex.Store({
5 state: {
6 todoList: [],
7 },
8});

What we’ve done above is creating a store with an initial state object. Our state at the moment contains an array called todoList which will be responsible for storing the to-dos in our application.

The next step is to connect the store we’ve created to our application in order to have access to it in our components. Open main.js file and refactor it to look like the code below

1import Vue from 'vue';
2import App from './App.vue';
3import store from './store';
4Vue.config.productionTip = false;
5new Vue({
6 render: (h) => h(App),
7 store,
8}).$mount('#app');

The change we’ve made to this file is importing the store we’ve created and injecting it into the root component. If you have the vue-devtools installed you can take a look at the store by opening your browser console and navigating to the Vue tab.

null

Mutations

To manipulate the state we’ve created we will need a mutation. Mutations help in modifying the state in the store, to modify a state we will need to commit a mutation.

Our to-do app will need some mutations to function, we want to be able to add to-dos, and update to-do items. Go back to your store.js and add this as a property after the state created earlier

1mutations: {
2 addTodo(state, title) {
3 state.todoList = [
4 ...state.todoList,
5 {
6 id: Math.random(),
7 title,
8 completed: false,
9 },
10 ];
11 },
12 addTodos(state, todos) {
13 state.todoList = todos;
14 },
15 updateTodo(state, todoId) {
16 state.todoList = state.todoList.map((item) => {
17 if (item.id === todoId) {
18 item.completed = !item.completed;
19 }
20 return item;
21 });
22 },
23}

We’ve created three mutations:

  • addTodo - for adding a single to-do item
  • addTodos - for adding an array of to-dos
  • updateTodo - for updating the completed status of a to-do item.

To commit a mutation we use the store.commit() function. It accepts a string which is the name of the mutation and an optional payload which is the data to be passed to the mutation. We will be using this mutations in subsequent sections.

Getters

Getters provide a way of getting a computed state from the store so instead of fetching a state in your components and then making computations on the state you can make the computations using a getter. This helps when more than one component needs to make use of the same computed state.

We will need a getter to compute the number of completed to-dos in our application

1// This should be pasted after the mutations property
2getters: {
3 completeTodosLength: (state) => {
4 const completeTodos = state.todoList.filter((item) => item.completed);
5 return completeTodos.length;
6 },
7},

If you notice from the code above you will see the getter accepts a state as a parameter that way it gives you complete read access to the state object. Getters can be fetched in components by either accessing it with store.getters or using a helper function from Vuex called mapGetters which is used in mapping store getters to local computed properties.

Actions

Actions are functions that dispatch mutations. They differ from mutations as they commit mutations instead of mutating the state directly. Since actions don’t modify a state directly they can be used to commit multiple mutations making it a better choice.

They can also be used to perform asynchronous operations, unlike mutations that are meant to be synchronous. A use case for actions is fetching data from an API and then committing a mutation that will modify the state based on the data received.

Let us create an action to get to-dos from an api and store them in the todoList state. Open the store.js file and refactor the actions property

1actions: {
2 getTodos({ commit }) {
3 fetch('https://jsonplaceholder.typicode.com/todos?userId=1')
4 .then((res) => res.json())
5 .then((data) => commit('addTodos', data))
6 .catch((error) => console.log(error));
7 },
8},

Actions receive an instance of the store as a context object which give us access to the same properties as that of the store like commit, state, and getter . The action we created makes a request to a fake API JSONPlaceholder to get an array of to-dos and then commits a mutation addTodos which was destructured from the context object to modify the todoList in state. In order to use an action we will need to trigger the action.dispatch() method which accepts the same parameters as a mutation.

Bringing Everything Together

We’ve been able to create state, mutations, and actions the next step is plugging all that into our components. Open the TodoList.vue and refactor the script with the code below

1<script>
2export default {
3 created: function() {
4 this.getTodos;
5 },
6 computed: {
7 todos() {
8 return this.$store.state.todoList;
9 },
10 todosCount() {
11 return this.$store.getters.completeTodosLength;
12 },
13 getTodos() {
14 return this.$store.dispatch('getTodos');
15 },
16 },
17 methods: {
18 updateTodo: function(todo) {
19 this.$store.commit('updateTodo', todo.id);
20 },
21 },
22};
23</script>

When this script runs we dispatch an action that we created earlier to get the to-dos from an api and then update the todoList state. We then get the list of to-dos from the store state in our todos function to use in our component. The number of completed to-dos is returned from the getter function getTodos and when a user toggles the checkbox of a to-do item it runs the updateTodo method which commits a mutation responsible for updating the completion status of a to-do item.

At this point, you should be able to see and update a list of to-dos on your browser

null

What’s left is making sure a user can create a new to-do item, so open the TodoForm.vue file and refactor the submitMethod to commit a mutation that adds a new to-do item to the state

1submitTodo: function(event) {
2 event.preventDefault();
3 this.$store.commit('addTodo', this.todo);
4 this.todo = '';
5}

Frontend Monitoring

Debugging a web application in production may be challenging and time consuming. Asayer is a frontend monitoring tool that replays everything your users do and shows how your app behaves for every issue. It’s like having your browser’s inspector open while looking over your user’s shoulder. Asayer lets you reproduce issues, aggregate JS errors and monitor your app’s performance. Asayer offers plugins for capturing the state of your VueX store and for inspecting Fetch requests and GraphQL queries. text Happy debugging, for modern frontend teams - Start monitoring your web app for free.

Conclusion

In this article, we have looked at the major concepts of Vuex: state, mutations, getters, actions, and how to integrate them into a Vue application. This is enough to get you going in creating Vue applications with Vuex, there are other advanced concepts not covered so be sure to check out the docs. The code for this article is available in this repo.

More articles from Asayer Blog

All about the Vue CLI

Learn all you need to know about using the Vue CLI to bootstrap your Vue apps

March 4th, 2021 · 6 min read

Low-Level Charts in React

What do you usually do when your project requires something more than casually using chart libraries? That's when a low level visualization library comes in handy.

March 4th, 2021 · 3 min read
© 2021 Asayer Blog
Link to $https://twitter.com/asayerioLink to $https://github.com/asayerioLink to $https://www.linkedin.com/company/18257552