Accessing the Vuex store from external JavaScript files is not allowed

The structure of my application can be found in the following link

Architecture of my app

For my specific use case, I am looking to utilize getters in the Axios interceptor

(/../src/app/shared/services/http-client/http-client.js)
to include the authorization token in the header. However, when I try to import the store from /../src/app/app-state.js, it results in the following error:

Uncaught TypeError: Cannot read property 'getters' of undefined
at eval (vuex.esm.js?2f62:340)
at Array.forEach (<anonymous>)
at assertRawModule (vuex.esm.js?2f62:339)
at ModuleCollection.register (vuex.esm.js?2f62:244)
at eval (vuex.esm.js?2f62:258)
at eval (vuex.esm.js?2f62:123)
at Array.forEach (<anonymous>)
at forEachValue (vuex.esm.js?2f62:123)
at ModuleCollection.register (vuex.esm.js?2f62:257)
at new ModuleCollection (vuex.esm.js?2f62:218)

app-state.js (vuex store) /../src/app/app-state.js

import Vue from 'vue';
import Vuex from 'vuex';
import createPersistedState from "vuex-persistedstate";
import { appName } from '../environment/environment'

import { authState } from './auth'
import { organizationState } from "./organization"

Vue.use(Vuex);

export default new Vuex.Store({
  state: {},
  mutations: {},
  actions: {},
  modules: {
    authState,
    organizationState
  },
  strict:false,
  plugins: [
    createPersistedState ({
      key: appName,
    })
  ]
});

main.js

import Vue from 'vue';

import './plugins';
import i18n from './plugins/i18n'
import './plugins/izitoast'

import App from './app/app.vue';
import DEFINES from './plugins/defines'

import './main.scss';
import router from './app/app-routes';
import store from './app/app-state';
import vuetify from './plugins/vuetify';

Vue.config.productionTip = false;
Vue.prototype.DEFINES = DEFINES;

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

**Organization module state (example of a module) **

import { list } from '../services'
import { getField, updateField } from 'vuex-map-fields';

/** Initial State */
const initialState = {
    loading: false,
    data: null,
    error: null
}

/**
 * Organization data mutations
 */
const mutations = {
    updateField,
    /** Organization data request */
    ORGANIZATION_DATA_REQUEST(state,payload) {
        Object.assign(state, {loading: true, data: payload})
    },

    /** Organization data success */
    ORGANIZATION_DATA_SUCCESS(state, payload) {
        Object.assign(state, {loading: false, data: payload})
    },

    /** Organization data error */
    ORGANIZATION_DATA_ERROR(state) {
        Object.assign(state, {
            loading: false,
        });
    },

    /** Organization data reset */
    ORGANIZATION_DATA_RESET(state) {
        Object.assign(state,...initialState)
    }
}

const actions = {
    async list(context){
        // 1. Initiate request
        context.commit('ORGANIZATION_DATA_REQUEST');

        // 2. Get data from API and handle error
        var response = await list().catch(error => {
            context.commit('ORGANIZATION_DATA_ERROR')
            throw error;
        })

        // 3. Set data in state
        context.commit('ORGANIZATION_DATA_SUCCESS', response)
        return response
    }
}

const getters ={
    getField,
    getList: (state) => {
        return state.data
    },
}


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

orjanization-state.js which combines all the feature states

import { organizationList } from "./shared/state"

export default {
    modules: {
        organizationList
    }
}

Answer №1

If you need to access Vuex modules in a JavaScript file, you can import the Vuex store and use it. Here is a snippet of my code where I am utilizing Vuex actions with Axios:

import Store from "@/store/index";
import axios from "axios";

const userRole = localStorage.role ? `${localStorage.role}` : "";

let config = {
    baseURL: process.env.VUE_APP_BASE_URL + userRole,
    headers: {
        Authorization: "Bearer " + localStorage.token
    },
};

const _axios = axios.create(config);

_axios.interceptors.request.use(
    function(config) {
        Store.dispatch("loader/add", config.url);
        return config;
    },
    function(error) {
        Store.dispatch("loader/remove", error.response.config.url);
        return Promise.reject(error);
    }
);

_axios.interceptors.response.use(
    function(response) {
        Store.dispatch("loader/remove", response.config.url);
        return response;
    },
    function(error) {
        Store.dispatch("loader/remove", error.response.config.url);
        return Promise.reject(error);
    }
);

export const $http = _axios;

I hope this code snippet proves to be useful for you.

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

What is the process for modifying the user agent?

I'm struggling with phantom, the node.js wrapper for phantomjs. This is the approach needed in native phantomjs. page.settings.userAgent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/5 ...

Issues with Firebase-admin preventing writing to the database are occurring without any error messages being displayed

Issues with Firebase admin writing to the database. The database is instantiated as follows: var db = admin.database(); A reference to the desired table is then set up: var systemsRef = db.ref("systems/"); A function is created to check if a 'sys ...

Unexpectedly, the child component within the modal in React Native has been resetting to its default state

In my setup, there is a parent component called LeagueSelect and a child component known as TeamSelect. LeagueSelect functions as a React Native modal that can be adjusted accordingly. An interesting observation I've made is that when I open the Lea ...

What is the process for creating a widget that can be seamlessly integrated into someone’s website and hosted on your own site

In relation to this previous question. After researching JSONP and conducting some tests, I've realized that I am completely clueless about what I'm doing... What is required? I am developing a customer service tool for people to integrate in ...

"Implementing a feature in Django that clears the input field upon clicking the clear button

I am working on a Django HTML file that includes an input field and a clear button. I need to clear the input field when the clear button is pressed. Is it necessary to use JavaScript for this task, or is there another way to achieve it? <form> ...

Having trouble obtaining information from the state with Pinia Store

Currently, I am delving into the world of the composition API and Pinia with Vue3. I am facing an issue while calling an external API to fetch data and store it in the state of my store. The problem arises when I try to access this state from my page - it ...

html css javascript, Is it possible to execute a script before a webpage finishes loading?

My current setup is similar to a lightbox feature, but I'm facing an issue where the script waits for the entire webpage to load before running. Is there a way to ensure that my script runs first without waiting for the webpage to fully load? CSS: # ...

Struggling with this mixed content problem

Encountering a problem while loading a js file: https://code.jquery.com/jquery-1.11.1.min.js, which is being loaded on my webpage in this manner: <script src="https://code.jquery.com/jquery-1.11.1.min.js"></script> Upon loading my webpage, an ...

Executing a function when a user chooses to exit a webpage using the @HostListener('window:beforeunload') method

Utilizing @HostListener('window:beforeunload') allows me to detect when a user navigates away from the page, prompting a dialog window to open. I wish for an event to be triggered or a method to be executed if the user chooses to leave the page. ...

Guide on switching the theme color in c# aspnet core using a toggle button within a partialview

Description I am looking to change the color scheme of my Bootstrap 5.3 theme by clicking a button within a partial view. The toggle button is customized to meet my specific requirements, and the chosen value is stored in a cookie for future reference. ...

What is the best way to set up jest to generate coverage reports for Selenium tests?

I recently made the switch to using jest for testing my JavaScript project after encountering coverage issues with mocha and chai. While my unit tests are providing coverage data, my Selenium tests are not. I've tried various solutions found in outdat ...

Adjusting Image Dimensions in jsPDF when Converting HTML to PDF

I have been experiencing some issues with image sizes while using jsPDF to convert HTML to PDF. I am currently on version 1.3.4 of jsPDF and below is the code snippet for reference: const tempElement = document.createElement("div"); tempElement. ...

What is the best way to utilize JavaScript for both server-side and client-side development, all while effectively sharing code between the two

Recently, I've been brainstorming a side project that I want to dive into for fun. As I explore options, I find myself searching for examples, libraries, and frameworks that could streamline the process of sharing code between the client and server. ...

Unlocking the true potential of JSON data encoding in PHP

While attempting to retrieve an object from my controller, the console.log(response) function displays the correct value: [ { "itemValue":100, "itemUnit":"2" } ] However, when trying to access the object using ...

There are currently no articles found that match the search query

Recently, I started working with Django, but I am facing an issue with slug. Whenever I send a request to the Slug, I encounter an error. The error message I receive is: Articles matching query does not exist. Furthermore, I am facing another error while ...

Utilize AJAX/JS and Django to seamlessly upload files

This is the form for my popup window. <div class="popup media-upload-form"> <div class="border cf"> <div class="close">X</div> </div> <form class="cf" action="" method="POST" enctype="multipart/form-data"> ...

Navigating using an Express API combined with a ReactJS single-page application

I've recently deployed a React site on Heroku, but I'm encountering an issue where the browser console is displaying html text instead of my user interface javascript. Check out my site And here's the link to my repository After some inves ...

The Next.js build version encounters an issue with 'auth' property being undefined and causes a failure

Our team has been happily working on a Next.js based website for the past few months. Everything was running smoothly without any major issues until yesterday when we encountered an error on the production version while using router.push: Cannot read prope ...

Looking for assistance with reviewing and optimizing Angular UI-Router implementation

I'm currently facing an issue with setting up routing for my angular portfolio. Despite checking my code against a previous app, I am unable to identify the error as there are no console logs when I compile. Can someone please review my code layout an ...

Is there a way to display an alert message when a button is clicked and perform

I want to create a form that functions like this: input + input = output This form will include two input fields for numbers with a plus + symbol between them. Additionally, there will be a Calculate button that, when clicked, will display a pop-up alert ...