Data Flow in VueJs – VueX Application

Data flow in Vuejs – Vuex Application

Vuex is a simple state management library for VueJs. It is very easy to use. It serves as a centralised store for all the components in an application, with rules ensuring that the state can only be mutated in a predictable fashion.

There are other implementation of flux-like state management patterns and libraries, but vuex has been designed to specifically work with Vue.js’s fast and simple reactivity system. This is accomplished through a well-designed API that provides a single source of truth for an application’s data as a singleton object. Vuex also provides explicit and trackable methods for asynchronous operations (actions), convenient reusable accessors(getters), and data altering capabilities (mutations).

Before starting give me a few moments to explain the meaning of the state, actions, mutations and store etc.

  1. State:  The state object will serve as the single source of truth where all the important application-level data is contained within the store.It is being watched by watcher and accessed by different components.
  2. Actions: The actions object where I define actions methods. Action methods are referred to as being “dispatched” and they’re used to handle asynchronous operations such as AJAX calls to an external service or API. Basically it will do following 3 actions:
    1. Request the server for student data
    2. Receive response from server and if data exists then mutate the state else throw an error.
    3. After mutating the state the components associated with that state will be re rendered by vue instance.
  3. Mutations: The mutations object provides methods which are referred to being “committed” and serve as the one and only way to change the state of the data. It will update state object and re-render the new value to Ui. So, Mutation is the only object which has proper right to mutate the state.
  4. Computed: This property is by default getter-only, but you can also provide a setter when you need it. Now when you run vm.fullName = 'John Doe', the setter will be invoked and vm.firstName and vm.lastName will be updated accordingly
computed: {
  fullName: {
    // getter
    get: function () {
      return this.firstName + ' ' + this.lastName
    },
    // setter
    set: function (newValue) {
      var names = newValue.split(' ')
      this.firstName = names[0]
      this.lastName = names[names.length - 1]
    }
  }
}

 

Vuex Data Flow

 Image courtesy: https://coligo.io/learn-vuex-by-building-notes-app/

In Vuex data flow, basically Components calls actions which  fetch the api from backend and if you got the success  then Actions will dispatch the events to mutation and  set the state object and if you get the error, actions will still does the same thing and  you will get to know using mutation. So, mutation handles everything whether its success or failure. Based on success or failure state object is set. Now in component using computed (getter) property, you will get the state object which you can easily renders in frontend.

Let’s check the simple example implemented below using vuex, actions, mutations.etc. which display user Paul Irish github’s follower.

So I have fetched the paul irish user detail in created hook. In this hook, you will able to access reactive data and events and make sure that templates and virtual DOM have not yet been rendered in created hook. So I fetched paul irish user detail from GitHub api before the DOM rendered. For that I have dispatched the event to store and action is ‘getFollowers’. ( you can check this on above code)  which is Requesting the server for GitHub user detail using axios. If you got the success, it will mutate using mutation ‘‘FOLLOWERS_SUCCESS’ and append the data to state object (here in followers object). If you get the error ,you will get to know using mutation. Computed properties are by default getter-only, but you can also provide a setter when you need it. Here I have used getter for paul irish’s followers. It’s pretty easy !

If you’re using Nuxt then instead of using created hook,  Nuxt has provided fetch method will call  every time before loading the component so you will get the same job done as created hook does. Fetch method takes many context object as parameter. so you need to add following code instead of created hook.

  fetch ({ store, params }) {
    return store.dispatch('followers/getFollowers', {})
  }

And of course, one important thing to note about fetch method is that it will run on the nuxt server if running on non-SPA mode to pre-render the app on server. If you don’t want to do that then you can dispatch events on mounted / created methods of Vue component.

 

 Tooling

Chrome has an excellent plugin to debug Vuex stores and even time travel between data. Its called “vuejs-devtools” and its quite handy when you are developing a large Vuex app with a big store. The feature of time travel enables you to rollback the application state to any past mutations, this sometimes helps in debugging scenarios which are caused by data mutations. The interface is quite sleek and easy to understand, you can even select a component and see its data changes in real time.

Happy Vueing!

 

References:
https://vuejs.org
https://nuxtjs.org
https://github.com/axios/axios
https://vuex.vuejs.org

Stay current with our latest insights



Leave a Reply