Manage shared nested modules across different modules in Vuex without redundancy

In my Vue.js application, I am using Vuex as the state manager. To ensure that certain states are shared across different components, I have created a nested state containing all the common information. This allows me to import it into multiple modules.

For instance, if I need the fileId in two separate modules, I approach it like this:

// Common file id store:
export default {
  state: {
    fileId: '',
  },
  actions: {
    setFileId({commit}, id) {
      commit('mutateFileId', id);
    },
  },
  mutations: {
    mutateId(state, id) {
      state.fileId = id;
    },
  },
};

I then import this module into other modules, for example:

// Store 1 where the file id is needed:
import fileIdModule from '@/store/modules/fileIdModule';

export default {
  modules: {
    fileIdModule,
  },
  actions: {
    whatEver({commit, dispatch}, param) {
      ...
      dispatch('setFileId', 1);
    },
  },
};

And in another store where the fileId is still required:

// Store 2 where the file id is needed:
import fileIdModule from '@/store/modules/fileIdModule';

export default {
  modules: {
    fileIdModule,
  },
  actions: {
    whatEver2({commit, dispatch}, param2) {
      ...
      dispatch('setFileId', 2);
    },
  },
};

The reason behind this approach is that the information is only necessary in a few stores out of many and as the application grows, importing duplicate modules can lead to issues...

However, one drawback of this method is that importing the same module multiple times can cause actions to be duplicated. For example, if I include the module in three places, the action will execute three times. This can be verified by adding a console.log statement inside the action:

  actions: {
    setFileId({commit}, id) {
      console.log('Mutating file id');
      commit('mutateFileId', id);
    },
  },

Even triggering the action from just one module will result in the console.log being printed twice.

Is there a way to share nested modules without causing duplication?

Answer №1

Vuex does not support shared nested modules.

However, you can still commit and dispatch to them from other modules without any issues. This feature may not be necessary after all.

Just remember to include {root: true} as the third argument when committing or dispatching from a module with namespaced: true:

commit('setFileId', 2, {root: true})

Answer №2

Absolutely, it is possible!

Implementing namespaces can help you determine the specific version of the module that you are using. For example...

Imagine you have the fileIdModule connected to both an ImageModule and a DocumentModule...

By utilizing namespaces, you can uniquely identify each action like dispatch('ImageModule/fileIdModule/setId')

and so on...

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Setting environmental variables throughout your application using create-react-app on the front end

Hey there! I have a simple Todo app with the client using create-react-app and the server running on node. I'm struggling to properly set environment variables across my app. I've placed my .env file in the root directory of the app, which curre ...

jQuery: event not firing for dynamically loaded elements via AJAX

In my jQuery/HTML5 front-end setup (with backend-generated code omitted), I am currently using version 1.8.3 of jQuery with no version conflicts. The front-end calls the following functions: detailAjaxCall("\/client\/orders\/detailsLoad&bso ...

Incorporating PHP in JS/jQuery AJAX for creating unique odd and even conditional layouts

My PHP code includes a loop that changes the layout of elements based on whether the $count variable is odd or even. For odd counts, an image appears on the left and text on the right. For even counts, it's the other way around. To load content dynam ...

What is the best way to convert an Angular object into a string using a for-loop and display it using $sce in AngularJS?

Currently, I am rendering a block of HTML and directives using $sce.trustAsHtml. To achieve this, I utilized a directive called compile-template which enables the use of ng-directives like ng-click and ng-disabled. While it is possible for me to pass sta ...

I encountered a parsing issue while trying to compile my Vue project

Issue: The component name "Header" should always consist of multiple words. Fix: Change the component name to a multi-word format according to Vue standards (vue/multi-word-component-names). ...

Breaking down and analyzing XML information

I have data that I need to retrieve from an XML file, split the result, parse it, and display it in an HTML element. Here is a snippet of the XML file: <Root> <Foo> <Bar> <BarType>Green</BarType> &l ...

Untangling REGEX URLs for Effective Filtering

I am currently working on creating a filter for a video list. I have successfully put together a string that includes all the values selected by the user for filtering. Right now, I am passing this string as a parameter through the URL. For example: NOTE ...

Developing a custom function that analyzes two distinct arrays and sends any corresponding pairs to a component

I'm in the process of developing a component that utilizes two arrays. These arrays are then mapped, and the matching pairs are sent down as props to a child component. The goal is to create a list component that retrieves the arrays from the backend ...

What is the process for obtaining a fresh token from Cognito using the frontend?

Currently, I am working with a react app that utilizes Cognito for user authentication. My main query revolves around making a call to Cognito using the refresh token in order to receive a new token. Despite researching various examples provided by Cognit ...

Generating dynamic input field values using jQuery in a CodeIgniter PHP framework application

I am facing an issue where I am unable to display the value from a dynamically created input field in the page controller. Below is the jQuery code used to append the dynamic input fields: var tableRow='<tr>'; tableRow+=' ...

Unable to view the HTML division

I am struggling with my website creation as I encounter issues with the .Main div. Despite setting background-color: orange; in the CSS, the color is not visible on the page. The inspector shows that it is positioned at 1440 x 0. Any assistance would be gr ...

Can Ajax be utilized to invoke an internal function within a web application?

Brand new to PHP, this is a whole new world for me. Currently, I am attempting to dynamically update a drop down list from 1-10 based on the selection of a previous drop down list. The initial drop down list allows you to choose tables numbered 1-35, whil ...

Resizing Elements with JQuery and Moving Them Forward

I have successfully made multiple objects draggable and resizable using the JQuery plugins for Draggable and Resizable. While dragging an object, it automatically comes to the front due to the stack option. However, when resizing an element without draggin ...

The functionality ceases to operate properly once a new element has been added

I am encountering an issue with the "click" action on a newly created element through a jQuery function, as it is not functioning properly. To demonstrate this problem, I have set up a JSFiddle at the following link (JSFiddle), however, please note that t ...

Establishing communication sessions with Express.js server and Vue.js client

I have encountered an issue with my project setup. I am utilizing an expressJS server to create a REST api server and a VueJS client using VueCLI. Folder Layout : .root ├── _server | ├── Files related to the server ├── _client | ├ ...

The proper technique for invoking a class method within a callback [prototype]

I am currently working with prototype 1.7 and developing a class that is designed to take a list of divs and create a tab interface. var customTabs = Class.create({ initialize: function(container, options) { this.options = Object.extend({ ...

What is the best way to utilize a variable retrieved from a mysql connection in NodeJS within an asynchronous function?

My current project involves scraping a website using Puppeteer. I am aiming to extract the date of the last post from my database and compare it with the dates obtained during the scrape. This way, I can determine if a post is already present in the databa ...

Distinguishing between creating controllers in AngularJS

I am a beginner in the world of AngularJS and I have come across two different examples when it comes to creating a controller. However, the one that is more commonly used doesn't seem to be working for me. The problem with the first example is that ...

Searching for attributes in a JSON document

Currently, I am dealing with a results API that provides me with a JSON file. My goal is to search for a specific property within this file. To achieve this, I first push the JSON data into an empty array and then iterate over it to retrieve the first obje ...

Using Vue Test Utils to simulate window scrolling

Looking for guidance on testing a window scroll event using vue-test-utils. Here is the Javascript code: export default { created () { window.addEventListener('scroll', this.topBResize); }, methods: { topBResize () { var he ...