What is the process for activating namespacing on a VueX module that has been imported?

I am currently utilizing a helper file to import VueX modules:

const requireModule = require.context('.', false,  /\.store\.js$/)
const modules = {}

requireModule.keys().forEach(filename => {
    const moduleName = filename
                   .replace(/(\.\/|\.store\.js)/g, '')
                   .replace(/^\w/, c => c.toUpperCase())
    modules[moduleName] = requireModule(filename).default || requireModule(filename)
})

export default modules

This script resides in @/store/modules/index.js and it gets imported by @/store/index.js:

import Vue from 'vue'
import Vuex from 'vuex'
import modules from './modules'

Vue.use(Vuex)
export default new Vuex.Store({
  modules,
  actions: {
    reset({commit}) {
      Object.keys(modules).forEach(moduleName => {
        commit(`${moduleName}/RESET`);
      })
    }
  }
})

Imported into Vue: @/main.js:

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'

Vue.config.productionTip = false

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

This approach works perfectly for all of my store modules! Each module is namespaced:

const initialState = () => ({})
const state = initialState()
const mutations = {
  RESET(state) {
    const newState = initialState();
    Object.keys(newState).forEach(key => {
          state[key] = newState[key]
    });
  }
} 
const getters = {}
const actions = {}

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

Now, I am attempting to import a package as a state module, something I have no prior experience with. When importing the package in @/store/modules/Auth.store.js:

import AmazonCognitoVuexModule from 'amazon-cognito-vuex-module';

const cognito = new AmazonCognitoVuexModule({
  region: process.env.VUE_APP_COGNITO_REGION,
  userPoolId: process.env.VUE_APP_COGNITO_USERPOOL_ID,
  clientId: process.env.VUE_APP_COGNITO_CLIENT_ID,
})

export default cognito

Upon trying to call the actions of this imported store module using $store.dispatch('Auth/...'), they are not found because they are not namespaced. To namespace this module "Auth", I might be overlooking something simple. Any assistance would be greatly appreciated.

Answer №1

After reviewing the documentation for this package on NPM, my initial attempt would be:

// source: https://www.npmjs.com/package/amazon-cognito-vuex-module
const store = new Vuex.Store({
  modules: {
    cognito: new AmazonCognitoVuexModule({
      region: '<region>',
      userPoolId: '<user pool id>',
      clientId: '<client id>'
    })
  }
});

The above code demonstrates importing it as a module (they used cognito, but you prefer auth - although it shouldn't affect functionality; I am following the naming convention from the official documentation). Therefore, your code should be updated as follows:

import Vue from 'vue'
import Vuex from 'vuex'
import modules from './modules'
import cognito from './path/to/cognito'

Vue.use(Vuex)
export default new Vuex.Store({
  modules: {
    ...modules,
    cognito,
  },
  actions: {
    reset({commit}) {
      Object.keys(modules).forEach(moduleName => {
        commit(`${moduleName}/RESET`);
      })
    }
  }
})

I cannot guarantee that this will work, but it is worth a try :)

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

Guide on showcasing the values from two text fields with autocomplete suggestions in a third text field

Hey there, I have a search form that takes values from two text fields and combines them to populate a third text field for querying. <form name="form1" method="post" action="" autocomplete="off" oninput="sea.value = password.value +''+ passw ...

An issue arises when attempting to utilize v-model with a file input

Is there a way to reset a file input field in Vue.js after uploading a file? I attempted to set the v-model value to null, but encountered an error message that said: File inputs are read only. Use a v-on:change listener instead. This is my current cod ...

When using React Final Form, the onBlur event can sometimes hinder the

What is the reason that validation does not work when an onBlur event is added, as shown in the example below? <Field name="firstName" validate={required}> {({ input, meta }) => ( <div> <label>First Name</label& ...

Generate JSON on-the-fly with ever-changing keys and values

I am new to coding and I'm attempting to generate JSON data from extracting information from HTML input fields. Can anyone guide me on how to create and access JSON data in the format shown below? { Brazilians**{ John**{ old: 18 } ...

Selenium javascript troubleshooting: encountering problems with splitting strings

Hello, I am new to using selenium and encountering an issue with splitting a string. <tr> <td>storeEval</td> <td>dList = '${StaffAdminEmail}'.split('@'); </td> <td>dsplit1 </td> < ...

Serving static files in Next.js with specific extensions without triggering a download

I'm facing an issue where I need to serve the stellar.toml file in domain/.well-known/stellar.toml with the content type as text/plain. The current configuration works only when the stellar file is saved without an extension. It is essential for me t ...

Is it possible for search engines to crawl and index specific pages within a web application that is powered by

I have created a web application with a dynamic JavaScript interface that communicates with the server through AJAX requests. The content of the page is determined by the data after the hashtag in the URL, which is fetched from the server and displayed acc ...

Using JSP in combination with JavaScript for creating dynamic templates

Implementing server-side HTML templating with JSP + JSTL allows for the generation of tables containing user data: <body> ... <table> <c:forEach items="${users}" var="user"> <tr> <td>${user ...

Generate a JSON array containing objects consisting of a combination of string and boolean values

My goal is to generate a list containing objects with names and boolean values by utilizing AJAX. This process is initiated in the following manner: $('.si-accordion').click(function () { $(this).siblings('.accordion_tab&apo ...

"Utilizing Jest Globals to Provide an Empty Input for a Function: A Step-by-

I have developed a function that outputs null when the input is empty: const testFunc = (param) => { if (param) { //blabla } return null; }; To verify the return null behavior with an empty param, I want to utilize describe...it...: describe( ...

Encountering a 404 error when trying to access the rxjs node_module

While attempting to compile an angular2 application, I encountered the following issue: Error: XHR error (404 Not Found) loading http://localhost:3000/node_modules/rxjs(…) systemjs.config.js (function(global) { // map tells the System loader whe ...

Having trouble retrieving the ID of a button?

I'm attempting to retrieve the ID of a button, but I seem to be getting the ID of the surrounding div instead. This is not the desired outcome. Here's my current approach: HTML <div class="container container-about container-login"> ...

Is it possible to place an open div panel between two tweets?

I'm in the process of developing a UI with Twitter feeds. I want to create a feature where a panel can be opened between two tweets, causing the tweet below to shift downwards. This function is commonly seen in tweet clients like TweetBot; as each new ...

Finding a workaround for the absence of a leftToggle feature in ListItem component of Material-UI

Is there a way to move the toggle element to the other side in Material-UI's listItem without using the leftToggle option? The documentation does not specify a leftToggle attribute, so I am looking for alternative solutions. I would like to align the ...

Organizing information into rows and columns with VueJS

I am currently working on organizing some data and I am looking for a way to present it in a table format with rows and columns using Vue Js. I want the display to look like this: https://i.sstatic.net/uEEbj.jpg The issue I am facing is that my current c ...

Using the Gmail API to retrieve the access token details by extracting the "code" parameter from the URL of a pop-up window

I am currently in the process of authenticating Gmail using OAuth2 for my web application. Upon receiving a URL from the server, the client opens a pop-up window with the following code: var win = window.open(data.google_oauth_url, `<h1>Gmail ...

Is Vue JSON.parse throwing an error due to whitespace?

When I receive a json_encoded return value from PHP, it appears fine. However, when passing this value to my Vue application, the format gets distorted. Here's what's happening: {"data":{"format":"d\/m\/Y H:i:s"}} In my Vue applicatio ...

The information transmitted from the Laravel controller is not syncing with the Vue variable as expected

I've been working on a web app with a dashboard using Laravel and Vue. While passing data from the controller to the Vue file, the data is received correctly. However, when I try to set it to a Vue variable, the value does not update in the variable. ...

The search function in Select2 is not displaying the desired result

I'm encountering an issue with the search functionality when it uses Ajax to load data from a JSON file. For example, if I search for Yemen, the record for Yemen does not get selected or highlighted properly. Here is the complete source code - could ...

Retrieving items from an array based on their class association

My challenge involves handling a list of items obtained using the following code: var searchResultItems = $(resultContainerId + ' li'); Each item in the search results can have different classes. How can I extract all items with a specific clas ...