This page looks best with JavaScript enabled

Avoid Vuex Boilerplate Code using Pathify

 ·   ·  ☕ 4 min read

Vuex is a lot of boilerplate.

Consider this user store -

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
//store/user.js
import axios from "axios";

export default {
  namespaced: true,
  name: "users",
  state: {
    users: [],
    loading: false,
    error: ""
  },
  mutations: {
    setUsers(state, users) {
      state.users = users;
    },
    setLoading(state, loading) {
      state.loading = loading;
    },
    setError(state, error) {
      state.error = error;
    }
  },
  actions: {
    fetchUsers({ commit, state }, params) {
      commit("setLoading", true);
      commit("setError", "");

      axios
        .get("http://myServer.com/api/get-users")
        .then(({ data }) => {
          commit("setUsers", data);
        })
        .catch(e => {
          commit("setError", "Error fetching user records.");
        })
        .finally(commit("setLoading", false));
    }
  }
};

Access this store from your view or component -

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<!-- views/User.vue -->
<template>
  <p v-if="error" class="error">{{error }}</p>
  <p>
    {{ users }}
  </p>
</template>

<script>
  import { mapState, mapMutations, mapActions } from "vuex";

  export default {
    computed: {
      ...mapState("user", ["users", "error"])
      // states are now accessible as any other computed property
    },

    methods: {
      ...mapMutations("user", ["setError"]),
      ...mapActions("user", ["fetchUsers"])
      // actions and mutations from store are now accessible
      //   .. as any other methods
    },

    mounted() {
      this.fetchUsers();
    }
  };
</script>

Getting state within components and invoking mutations is laborious and not-so-pretty. If you want to just set one array ‘users’ you need a mutation (setUsers), a state (users), and an action requiring this state. The views and components dependent on the store will use these states and methods - this is way lot of work.

I am lazy.

So, Pathify.

Pathify will rescue you from all the variables and methods that you need to set, and wiring that you need to do. It uses get(), set(), sync() and call() methods to enable you to work with Vuex states in a much more easy way.

First, you have to install Pathify.

1
npm i vuex-pathify --save

Use Pathify plugin for Vuex -

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
// store/index.js

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

import user from "./user";
import account from "./account";

Vue.use(Vuex);

export default new Vuex.Store({
  namespaced: true,
  name: "global",
  plugins: [pathify.plugin], // activate plugin
  modules: {
    user,
    account
  }
});

Pathify lets you write minimal code in your store and in your views and components where you use the store.

In the store -

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//store/user.js
import { make } from "vuex-pathify";

const state = {
  users: [],
  error: "",
  loading: false
};

const mutations = make.mutations(state);
// automatically create mutations (e.g. setLoading, setError)

const actions = {
  // automatically create `setUsers()` action
  ...make.actions("users")
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};

In the views/components -

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<!-- views/User.vue -->
<template>
  <p v-if="error" class="error">{{error }}</p>
  <p>
    {{ users }}
  </p>
</template>

<script>
  export default {
    computed: {
      users: get("user/users"),
      error: get("user/error")
    },

    methods: {
      fetchUsers: call("user/fetchUsers")
    },

    mounted() {
      this.fetchUsers();
    }
  };
</script>

Now, this may not look like much in a simple example. But, you will be accessing or modifying tens or even hundreds of variables, and calling at least 3-4 functions from a view in a typical application. Pathify can greatly reduce the number of ‘dummy’ statements that you have to write to get everything working in store and UI.

On the flip side -

  • committing to Pathify will change how you write your store and is an additional API. Everyone in your team must be on the same page to reduce code inconsistency
  • Vue 3 may change the way stores are structured (e.g. mutations may go away) and may even reduce the boilerplate of Vuex. Using Pathify may produce new/unknown issues at that time (npm modules can be a PIA if not supported through versions)
Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things