Two less known facts about Vuex

Nicolò Maria Mezzopera

Nicolò Maria Mezzopera

Mar 3, 2019
2 min read
Share on Twitter or LinkedIn

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();

Don't miss out anything about Vue, your favourite framework.

Subscribe to receive all the articles we publish in a concise format, perfect for busy devs.

Related Articles

Creating a Store without Vuex in Vue.js 2.6

Tip on creating a simple store in Vue.js 2.6 by using the new Observable API

Alex Jover Morales

Alex Jover Morales

Feb 17, 2019

How to test Web Workers with Jest

Do you know the best part of Web Workers? They can speed up heavy tasks on your UI. But, have you tried testing them? Is not that easy... until now.

Andrea Stagi

Andrea Stagi

Oct 20, 2020

How to use the new Fetch in Nuxt.js

The Nuxt team is on fire, releasing new stuff every week! In this tip Samuel shows you a feature that might've gone unnoticed... till now.

Samuel Snopko

Samuel Snopko

Sep 7, 2020

Sponsors

VueDose is proudly supported by its sponsors. If you enjoy it, consider supporting it to ensure the project maintainability.

Silver
Learning Partner