Solomon Eseme I'm a software developer focused on building high-performing and innovative products according to best practices and industry standards. I also love writing about it. https://about.me/solomoneseme

How to create a custom Vuex plugin

2 min read 709

How to Create a Custom Vuex Plugin

Vuex plugins are among the most advanced and useful concepts in Vuex. They have a wide variety of use cases, from data persistence, to Slack Notifier, to enhacing Vuex itself.

A Vuex plugin is simply a function that receives the store as the only argument. In simple terms, a plugin is a function that is triggered/called when a certain type of mutation or action is called in Vuex.

In this tutorial, we’ll walk you through how to create a custom Vuex plugin.

Subscribing to mutation hooks

When subscribing to mutation hooks, remember that plugins are not allowed to mutate the state directly. They can only trigger changes by committing Vuex mutations.

The Mutations Hook exposes two attributes:

  1. mutation.type is used to determine the name of the mutation/action that is triggered
  2. mutation.payload is used to retrieve the data to be committed
    export default (store) => {
    store.subscribe((mutation) => {
    if (mutation.type === "STORE_ERRORS") {
    // Alert Slack here
    console.log(mutation.type, mutation.payload)
    }
    });
    };

Subscribing to action hooks

The subscribeAction() works exactly like subscribe(), except that it’s sending type and payload information about the Vuex action being called, not the mutation.

  store.subscribeAction((action) => {
    if (action.type === "getTodos") {
      // Alert Slack here
      console.log(action.type, action.payload)
    }
  });

The subscribeAction was added in Vuex 3.1.0. If you haven’t already, you might want to upgrade it.

Building the Slack Notifier Vuex Plugin

Let’s combine what we’ve learned so far to build a custom Vuex plugin that will notify a Slack channel of any errors when committing our state.

Create plugin class

Create a file in the plugins folder

mkdir plugins

touch SlackNotifier.js

Create STORE_ERRORS Mutation

Next, we’ll create a Vuex mutation called STORE_ERRORS. You can implement this Vuex mutation to store errors in state or display an error alert using various packages, like sweetalert.

We made a custom demo for .
No really. Click here to check it out.

In our case, we’ll simply send the errors to our ErrorService to process and display them on our components.

  mutations: {
    // ....

    STORE_ERRORS: (state, error) => {
      // Call Error Service here
      ErrorService.onError(error);

      // Store error to state(optional)
      if (error.response) {
        state.errors = error.response;
      }
    },

    // ...
  },

Whenever this Vuex Mutation is called, we want our Vuex plugin to trigger and send the error to Slack.

Building SlackNotifier

Open your SlackNotifier class and paste the code below. Remember to modify your code to suit the type of Vuex mutations and actions you want to watch. In our case, it’s the STORE_ERRORS mutation and all our Vuex actions (you may or may not want to do that).

import axios from "axios";
const url = // Your Slack Webhook here;
export default (store) => {
  store.subscribe((mutation) => {
    if (mutation.type === "STORE_ERRORS") {
      // Alert Slack here
      errorSlackAlert(mutation.payload);
    }
  });
  store.subscribeAction((action) => {
    // Alert Slack here
    vuexActionSlackAlert(action.type);
  });
};
function vuexActionSlackAlert(type) {
  const data = {
    username: "Action Notifier",
    icon_emoji: ":bangbang:",
  };
  data.text = `Vuex "${type}" action was excuted`;
  data.attachments = [];
  data.attachments = [
    {
      color: "#eed140",
      fields: [
        {
          title: "Environment",
          value: "Development",
          short: true,
        },
      ],
    },
  ];
  postToSlack(data);
}
function errorSlackAlert(payload) {
  const data = {
    username: "Error Notifier",
    icon_emoji: ":bangbang:",
  };
  data.text = payload.message;
  if (payload.resource) {
    data.text = payload.resource.message;
  }
  data.attachments = [];
  data.attachments = [
    {
      color: "#eed140",
      fields: [
        {
          title: "Environment",
          value: "Development",
          short: true,
        },
        {
          title: "StackTrace",
          value: payload.fileName,
          short: true,
        },
      ],
    },
  ];
  postToSlack(data);
}
function postToSlack(message) {
  axios
    .post(url, JSON.stringify(message))
    .then((result) => console.log(result))
    .catch((error) => console.log(error));
}

Read the official docs for more on the the Slack API.

store.subscribe(…….) gives us access to all the Vuex mutations. Whenever a mutation is called or executed, check to make sure the type of mutation called matches STORE_ERRORS. If it does, call errorSlackAlert to pass along the payload, which formats the message according to how Slack wants it. Then, call postToSlack to post the message to the Slack webhook.

Slack Error Notifier Bot

The same thing happened with store.subscribeAction(…….), except this time we’re not checking for any specific type of Vuex action but notifying Slack about any action that is triggered.

Slack Action Notifier Bot

Conclusion

If you’ve made it this far, you should have a deeper understanding of plugins in Vuex. You should also have the experience and know-how required to build your own custom Vuex plugin.

If you want to contribute to the Vuex Slack Notifier on Github, send a PR 😎

Experience your Vue apps exactly how a user does

Debugging Vue.js applications can be difficult, especially when there are dozens, if not hundreds of mutations during a user session. If you’re interested in monitoring and tracking Vue mutations for all of your users in production, try LogRocket. https://logrocket.com/signup/

LogRocket is like a DVR for web apps, recording literally everything that happens in your Vue apps including network requests, JavaScript errors, performance problems, and much more. Instead of guessing why problems happen, you can aggregate and report on what state your application was in when an issue occurred.

The LogRocket Vuex plugin logs Vuex mutations to the LogRocket console, giving you context around what led to an error, and what state the application was in when an issue occurred.

Modernize how you debug your Vue apps - .

Solomon Eseme I'm a software developer focused on building high-performing and innovative products according to best practices and industry standards. I also love writing about it. https://about.me/solomoneseme

Leave a Reply