Two less known facts about Vuex

#Vuex

This tip comes from a special invitee: Nicolò Mezzopera, a web developer on Pulilab and a great person! We even organized a Vue.js meetup in Budapest together this year!

If you happen to be in Verona on April 12th, he’s giving a talk in the Vue Day Italy 2019. It can be your chance to meet him 😉.

Enough introduction, let’s go to the tip!


When using Vuex in our Vue.js components we tend to forget the amazing API that it exposes beside the mapping functions.

Let’s see what we can do with it, but first let’s create a basic store for our examples:

const store = new Vuex.Store({
  state: {
    count: 0
  },
  getters: {
    getCountPlusOne: state => state.count + 1
  },
  mutations: {
    increment(state) {
      state.count++;
    }
  }
});

Watch

The watch method is the most useful to integrate Vuex with external code, be it in your awesomeService or in your catchAllAuthUtils.

This is how to use it:

const unsubscribe = store.watch(
  (state, getters) => {
    return [state.count, getters.getCountPlusOne];
  },
  watched => {
    console.log("Count is:", watched[0]);
    console.log("Count plus one is:", watched[1]);
  },
  {}
);

// To unsubscribe:
unsubscribe();

What we are doing is to call the watch method with two functions, one to return what part of the state and/or getters we want to keep an eye on and the other with the function that we want to invoke when state.count or getCountPlusOne change.

This is extremely useful to integrate with react code or angular or even… JQuery!

See the example in this CodeSandbox.

SubscribeAction

Sometimes instead of watching a store property change it’s more useful to react to a specific action, login and logout come in mind, vuex has us covered with subscribeAction.

Calling subscribe adds a ‘callback’ that is run at every action and that we can use to call custom code.

Let’s use it to start and stop a global spinner before and after every action!

const unsubscribe = store.subscribeAction({
  before: (action, state) => {
    startBigLoadingSpinner();
  },
  after: (action, state) => {
    stoptBigLoadingSpinner();
  }
});

// To unsubscribe:
unsubscribe();

Remember you can read this tip online (with copy/pasteable code), and don’t forget to share VueDose with your colleagues, so they also know about these tips as well!

See you next week.

Alex

Do you want to sponsor a VueDose tip? Send an email to info@vuedose.tips and have more info!

Start saving time and get a tip about the Vue ecosystem every week, right in your inbox.