Unlocking the secrets of integrating Vuex store with JavaScript/TypeScript modules: A comprehensive guide

I am working on a vue application and I have a query.

How can I access the store from javascript/typescript modules files using import/export?

For example, if I create an auth-module that exports state, actions, mutations:

export const auth = {
  namespaced: true,
  state,
  actions,
  mutations,
  getters,
};

In my app, I import the module to my store like this:

Vue.use(Vuex);

export const store = new Vuex.Store({

  modules: {
    auth,
  }
});

Now, I want to create an interceptor (inside my auth-module) for my http calls to add the token from the store.

Vue.http.interceptors.push((request: any) => {
    // ---> How do I access store.state.token???
    // request.headers.set('Authorization', 'Bearer TOKEN');
  });

But how can I access the state of the store without depending on my app? import {store} from './store' but is it possible to import the store instance from the vue or vuex module directly.

Answer №1

To implement this functionality, you can utilize a Plugin.

  1. Upon using the Plugin, you will receive access to the store instance.
  2. By subscribing to the instance, you can obtain the state, extract the token from it, and store it in a local variable.
  3. Within the Interceptor, retrieve this module-global variable as needed.

Below is a tailored solution for your situation:

StoreTokenInterceptorPlugin.ts

import Vue from 'vue';
import VueResource from 'vue-resource';
import { get } from 'lodash';

Vue.use(VueResource);

export const StoreTokenInterceptorPlugin = (store: any) => {
  let token: string | null = null;

  (Vue.http.interceptors as any).push((request: any) => {
    if (token && !request.headers.get('Authorization')) {
      request.headers.set('Authorization', `Bearer ${token}`);
    }
  });

  store.subscribe((mutation: any, state: any) => {
    token = get(state, 'auth.token') || null;
  });
};

within your application's store:

import Vue from 'vue';
import Vuex from 'vuex';

import { auth, StoreTokenInterceptorPlugin } from '@modules/auth';

Vue.use(Vuex);

export const store = new Vuex.Store({
  state,

  modules: {
    auth,
  } as any,
  ....
  plugins: [StoreTokenInterceptorPlugin],
});

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

A tutorial on creating circular patterns within a pyramid structure using p5.js and matter.js

I've been attempting to create a pyramid shape using multiple circles, similar to this: balls in pyramid shape To achieve this, I've developed a 'Balls' class: class Balls { constructor(x, y, radius, color, ballCount) { this.x = ...

Prevent caching of JavaScript variables in EJS mode

Is there a way to turn off ejs cache? I came across a solution: ejs.clearCache() However, this method requires an instance of ejs to work. Currently, I am only using: app.set('view engine', 'ejs'); Therefore, I am unsure how to cle ...

Tips for customizing the timing of a Bootstrap modal's opening delay?

I have integrated gem "bootstrap-sass", "~> 2.3.0.0", which indicates that I am utilizing Bootstrap 2. Detailed information on the modal can be found here. The code for my custom modal looks like this: #Modal.modal.hide.fade{"aria-hidden" => "true" ...

Autocomplete is failing to provide any results

I am experiencing an issue with the autocomplete script as it is not displaying any names under the input field. Below is the code snippet from my index file: <head> <html lang="en"> <meta charset="utf-8"> <meta na ...

What is the process of integrating a Vue.js client into an established Node.js API?

I've successfully developed a node.js API with various endpoints and also built a vue.js client app to interact with the API. Everything is working seamlessly at the moment. However, I've encountered an issue where I need both applications to run ...

Insert a new store into an existing IndexedDB database that is already open

After opening and passing the onupgradeneeded event in IndexedDB, is there a way to create a new store? My attempted code: var store = db.createObjectStore('blah', {keyPath: "id", autoIncrement:true}); This resulted in the following error mess ...

Issue encountered when displaying various data options in the dropdown menus within a modal window

My goal is to display a modal when a button is clicked. The modal renders perfectly fine, but I am facing an issue with duplication of dropdowns inside the modal when the "add more" button is clicked. The main issues are: 1. Selecting the first option in ...

Tips for implementing FontAwesome in Nuxt3

I'm facing some issues trying to implement FontAwesome in my NuxtJS project, and for some unknown reasons, it's not working as expected. Let's take a look at my package.json: { "private": true, "scripts": { " ...

Error: Unable to find the specified "location.ejs" view in the views directory

I am encountering the following error - Error: Failed to find view "location.ejs" in views folder "e:\NodeJs_Project\geolocationProject\views" at Function.render Your help in resolving this issue would be greatly appreciated. server.js ...

What causes arguments to be zeroed out during a WebAssembly imported function call?

I created a WASM module manually that can be decompiled using wasm2wat to reveal the code below. (module (type (;0;) (func)) (type (;1;) (func (param i32 i32))) (import "std" "print" (func (;0;) (type 1))) (func (;1;) (type 0) ...

jQuery functionality restricted to desktop devices

I am attempting to disable a jQuery function specifically for mobile devices. I found some instructions that seem helpful on this page. Unfortunately, following the instructions did not work for me. Here is the code snippet I have: var isMobile = /Androi ...

What is the best way to interpret the data from forkjoin map?

As a newcomer to angular and rxjs, I am seeking guidance on how to properly retrieve data from forkJoin using a map function. ngOnInit(): void { this.serviceData.currentService.subscribe(service => this.serviceFam.getAllFamilles().pipe( ...

"Use jquerytools to create a dynamic play/pause button functionality for scrollable content

Greetings! I am currently working on creating a slide using Jquerytools. Here are some helpful links for reference: To view the gallery demonstration, please visit: For information on autoscroll functionality, check out: If you'd like to see my cod ...

AngularJS 2: Modifications to templates or components do not automatically reflect in the user interface

My background is in Angular 1, where everything worked seamlessly. However, I am encountering serious issues trying to create a basic application using Angular 2 in Visual Studio. After carefully following the "5 minute tutorial" and getting it to work, I ...

Processing two Array Objects can be achieved without resorting to the EVAL function

I have two objects that I need to process. obj1 contains an array of objects with formulas. obj2 holds the values needed for the calculations. I am looking for a way to process and calculate both objects in order to obtain a result where the keys present ...

Creating a Paytm payment link using API in a React Native app without the need for a server

Suppose a user enters all their details and the total cost of their order amounts to 15000 rupees. In that case, the app should generate a Paytm payment link for this amount and automatically open it in a web view for easy payment processing. Any suggesti ...

pressing the button again will yield a new outcome

I am looking to disable a button (material ui) when it is clicked for the second time by setting disabled={true}. Unfortunately, I have not been able to find any examples related to this specific scenario on StackOverflow. <Button onClick={this.s ...

It is not possible to include a new property to an object while inside a function

Looking to add a property to an object? Check out the code below: import React from 'react'; import { Link } from 'react-router-dom'; const Question = () => { let active; const handleClick = (iconName) => { active = {}; ...

Disappear scrollbar when overlay is activated

How can I hide the scroll bar when an overlay is displayed on my page? .overlay{ display: none; opacity:0.8; background-color:#ccc; position:fixed; width:100%; height:10 ...

What is the method to retrieve values passed to the next() function in Node.js?

For my current project, I am utilizing Node.js in combination with Express.js to develop the back-end. In middleware functions, next() is commonly used to progress through the chain until reaching the final app.VERB() function. My question is, at what poi ...