How to Manage State in vueJs effortlessly

“Tanisk, I recently Started learning vuejs? What State Management solution should I use?”— Eric

“Hi Eric and thanks for the DM. This is perhaps the most often asked question in the application developers community.

To understand it best, perhaps i have one similar question for you:

“What toppings do you like on your pizza?”

Seriously. How am I supposed to know what you like on your pizza,

And how am I supposed to know which State Management solution is going to be best for your app.

 There are plenty of good State Management solutions out there for vuejs apps but not all of them are going to be a good fit for you.

If you already know reactjs and you’re really good with Redux,  then it makes sense to use vuex because it’s also based on the flux pattern.

In this article, we will use vuex to manage State in vueJs effortlessly

I’m a Big fan of official documentation of vue so let’s start with that.

Vuex is a state management pattern + library for Vue.js applications. It serves as a centralized store for all the components in an application.

In layman’s term, Vuex allows you to create one data store which can be accessed by all components in app. This store is also known as single source of truth.

Installation

// npm
npm install vuex

// yarn
yarn add vuex

Setting up Vuex

Once you have successfully installed Vuex in your VueJS application,

you can set your application to use it by doing the following within your main.js file:

import Vue from "vue";
import Vuex from "vuex";
import App from "./App";
import router from "./router";
// Import the store from the file we are about to create
import { store } from "./store/index.js";

Vue.config.productionTip = false;

Vue.use(Vuex);

/* eslint-disable no-new */
new Vue({
  el: "#app",
  // tell our vue instance to use our store
  store: store,
  router,
  components: { App },
  template: "<App/>"
});

Vuex 5 Core Concepts:

1 – State : App level state/data

4 – Mutations : Mutate the state (update the data)

3 – Actions : Called from components to commit a mutation

2 – Getters : Get pieces of state or computed value from state

5 – Modules : Each module can have its own state, getters, action, mutations

1 – State:

State is applications data. This could be as simple as this if we wanted to store a ‘username’ value within our application:

import Vuex from "vuex";
import Vue from "vue";

export const store = new Vuex.Store({
  state: {
    username: "taniskjha"
  }
});

2 – Mutations

The only way to actually change state in a Vuex store is by committing a mutation.

if you wished to update the username within our state object above,

you can do it through a mutation. This mutation has to be invoked through the use of an action which we’ll cover in the next block.

Let’s take a look at how we would create a username mutation

which would allow us to change our username value within our state object:

import Vuex from "vuex";
import Vue from "vue";

export const store = new Vuex.Store({
  state: {
    username: "taniskjha"
  },
  mutations: {
    updateUserName(state, newUsername) {
      state.username = newUsername;
    }
  }
});

3 – Actions

Actions are similar to mutations, the differences being that, Instead of mutating the state, actions commit mutations.

What this means is that if we want to update the username of our state object above,

We need to trigger an action using the store.dispatch() method and passing in the string username of the action we wish to update.

The main reason we have this level of abstraction away from our mutations is so that we can make asynchronous requests.

All mutations have to be synchronous, so by having our actions perform any asynchronous code and then commit-ing the result to a mutation.

Let’s take a look in below example:

import Vuex from "vuex";
import Vue from "vue";

export const store = new Vuex.Store({
  state: {
    username: "taniskjha"
  },
  mutations: {
    updateUserName(state, newUsername) {
      state.username = newUsername;
    }
  },
  actions: {
    updateUserName({ commit }) {
      commit("updateUserName", "aryanjha");
    }
  }
});

Whenever we trigger the updateUserName action, the username stored within our state object will subsequently be updated to aryanjha.

We can trigger an action by doing the following:

store.dispatch("updateUserName"); 

4 – Getters

If more than one component needs to make use of username, we have to either duplicate the function,

Or extract it into a shared helper and import it in multiple places – both are less convenient

Vuex allows us to define “getters” in the store. You can think of them as computed properties for stores.

Like computed properties, a getter’s result is cached based on its dependencies,

And will only re-evaluate when some of its dependencies have changed.

For example, if we had a username set to tanisk originally, and we had a getter that returned ‘t’ as the first initial, this ‘t’ result would be cached for us.

However, when we update the username by dispatching an action, this result would be updated to a as that would be the initial of aaryanjha.

import Vuex from "vuex";
import Vue from "vue";

export const store = new Vuex.Store({
  state: {
    username: "taniskjha"
  },
  mutations: {
    updateUserName(state, newUsername) {
      state.username = newUsername;
    }
  },
  actions: {
    updateUserName({ commit }) {
      commit("updateUserName", "aryanjha");
    }
  },
  getters: {
    firstInitial: state => {
      return state.username[0];
    }
  }
});

If you are doing Queries such as filtering a large list of objects then getters becomes very useful.

5 – Modules

Due to using a single state tree, all state of our application is contained inside one big object.

However, as our application grows in scale, the store can get really messy.

To help with that, Vuex allows us to divide our store into modules

Each module can contain its own state, mutations, actions, getters, and even nested modules

Closing Notes:

I hope all of you would have enjoyed reading this article. We at codeum.io always aspire to deliver the best stuff that we can serve to our readers. Your satisfaction is our topmost priority.

In the end, we request you to share this post to all social media platforms of your choice. And please float it into your friend circle as well.

Thanks for reading, If you have any questions , please ask questions in the comments below.

More Posts:-

I Was Scared of JS Promises In 2017, But I’m Super-Brave in 2020 (Learn My Tricks)

Step by Step plan that will Get You From ZERO to PASSING a coding interview (at Google, Facebook, Amazon)

Calling All New Developers. Understand How do JS closures work?

The Ultimate Guide to become a full stack web developer in 3 easy step

7 Amazing Array Methods to Boost your Javascript Skills Today

33 Most Powerful linux Commands To Run in Terminal

Who Else Wants to Clear confusion about Javascript Hoisting [Step-by-Step]

Tanisk jha

Mission-Driven Self taught Software Developer with a passion for thoughtful UI Design, collaboration and writing.
Tanisk jha

One thought on “How to Manage State in vueJs effortlessly

  1. Your are unpredictable & one of the great dedicated person towards work which I have seen, proud to be your friend.

    Thanks,
    Kanaka
    Hyderabad

Leave a Reply

Your email address will not be published. Required fields are marked *