Vuex: one mutation to rule them all

published at Oct 25, 2019
#Vuex#Vuejs

Vuex is a good library, helping a lot in large projects. However, the necessity to write a mutation each time we want to update something is tedious. If you want to develop faster when using vuex, you need to refactor your methods. Let me introduce how I implemented a generic mutation method.

// src/store/index.js

import Vue from 'vue'
import Vuex from 'vuex'
import exampleModule from './example'

import set from 'lodash/set'

Vue.use(Vuex)

export default function () {
  const Store = new Vuex.Store({
    modules: {
      exampleModule,
    },

    state: {
    },

    getters: {
    },

    mutations: {
      /* 
      this is the generic mutation I talked about. Just as simple as that, thx to the set method of Lodash library.
      With that method, you can pass any object (with nested properties if you want) by using dot notation. More on that later
      */
      mutate (state, payload) { 
        set(state, payload.property, payload.value)
      },
    },
    actions: {
    },
    strict: process.env.DEV,
  })

  return Store
}

The mutate method is the crucial one. I use it every time I need to assign some values in my store. Very useful. You can use it in actions from different modules. For example, in a Quasar project, you can call it like that:

// src/store/example/actions.js

export function someAction ({
  commit
}, payload) {
  return new Promise((resolve, reject) => {
    this._vm.$axios.post('/some-action', payload)
      .then(r => {
        commit('mutate', {
          property: 'whatever.object.you.have',
          value: r.data
        }, {
          root: true // don't forget to pass this second argument when you want to call a root mutation
        })
        resolve(r)
      })
      .catch(e => {
        reject(e.response)
      })
  })
}

There is some limitations though if you over use this method. It's true that's practical but that kind of methods lacks of readability. If your mutation is an important one for your project, I suggest writing a specific mutation. But most of the time, you'll probably have minor updates to do in your store. In that case, using a generic mutation is fine and will ease your productivity.

Resources