Front-End

Choosing Good Vuex Mutation Types

VueJS

Vue.js Views

A Vue.js web app include views that load data from the server side. Such loading usually involves showing a loader (spinner) and then showing the data once it arrives at the store.

Vuex

Vuex is the standard state management approach for Vue.js.

Views display data using getters on the Vuex store.

Which Mutations Types Are Best

How do you structure your actions to naturally correspond to the views loading process?

We found it easy to start with the mutation types. These are just strings constants, so it is simple to think with them and then define the actions around them.

Let us consider the common case of fetching data from the server.

Fetching Data from the Server Side3

One can think of two alternatives for mutations types for fetching data from the server side:

  1. 1. PROCESS_DATA - to signal to the views we are loading, and DATA_RECEIVED - to signal that the data arrived
  2. 2. LOAD_DATA - to tell the store to fetch data, and DATA_RECEIVED - to signal that the data arrived

We find the first alternative to be better. As it fits the natural flow of the view: first - a loader (spinner), and then the data arrives.

It lets you structure you actions as:


async getDeployments({ commit, state }, { skip, limit }) {

    // signal to the views that we are loading data
    commit(types.PROCESSING_DEPLOYMENTS);

    const results = await deployments.getDeployments(skip, limit);

    commit(types.RECEIVED_DEPLOYMENTS, { results });

}

And you call the action simply from the view.

 
onClick() {
	getDeployments({ skip, limit });
}

Yoram Kornatzky

Yoram Kornatzky