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.
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:
mutation.type
is used to determine the name of the mutation/action that is triggeredmutation.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) } }); };
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.
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.
plugin
classCreate a file in the plugins
folder
mkdir plugins touch SlackNotifier.js
STORE_ERRORS
MutationNext, 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.
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.
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.
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.
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 😎
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.
LogRocket is like a DVR for web and mobile 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 — start monitoring for free.
Hey there, want to help make our blog better?
Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.
Sign up nowToast notifications are messages that appear on the screen to provide feedback to users. When users interact with the user […]
Deno’s features and built-in TypeScript support make it appealing for developers seeking a secure and streamlined development experience.
It can be difficult to choose between types and interfaces in TypeScript, but in this post, you’ll learn which to use in specific use cases.
This tutorial demonstrates how to build, integrate, and customize a bottom navigation bar in a Flutter app.