Taha

Reset Vuex Module State Like a Pro

Vuex is a great tool to manage the state of your Vue app. If your app is large, it would be inefficient to put all of your app's state inside a single state object. In this case, it's better to divide the store into multiple small modules.

A vuex module can represent anything dividable in your app. It can, for example, represent a modal box, multi-step form, cart, you name it.

These module states would, of course, change while the app is running and being used. Let's take the cart module as an example. A cart should have a list of items/products that the user adds to it. This list should be cleared when the user either removes the items or complete the purchase.

In vuex terminology, clearing the cart means resetting the state of the module. So if the items array has values, we would replace it with an empty array. And if the status has pending value we would change it back to empty for example.

I know why I need to reset vuex module state, now show me how

Let's continue with our cart example. We would have our modules stored inside a modules directory, like this:

store
├── index.js
└── modules
    └── cart.js

Here's how cart.js would look like with the resetting code:

const getDefaultState = () => {
  return {
    items: [],
    status: 'empty'
  }
}

// initial state
const state = getDefaultState()

const actions = {
  resetCartState({ commit }) {
    commit('resetState')
  },
  addItem({ state, commit }, item) {
    /* ... */
  }
}

const mutations = {
  resetState(state) {
    Object.assign(state, getDefaultState())
  }
}

export default {
  state,
  getters: {},
  actions,
  mutations
}

So the core idea here is to create a factory function, getDefaultState, that returns a fresh instance of the default state object. We used it twice in our code: when initializing it and when resetting it.

Now whenever you want to reset the state of this module, you just need to call the action resetCartState from anywhere in your code.

Taha Shashtari

I'm Taha Shashtari, a full-stack web developer. Building for the web is my passion. Teaching people how to do that is what I like the most. I like to explore new techniques and tools to help me and others write better code.

Subscribe to get latest updates about my work
©2024 Taha Shashtari. All rights reserved.