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

Setting a random number as an id in the constructor in Next JS can be achieved by generating a

What steps can be taken to resolve the error message displayed below? Error: The text content does not match the HTML rendered by the server. For more information, visit: https://nextjs.org/docs/messages/react-hydration-error Provided below is the code i ...

In what situations is it beneficial to utilize inherited scope, and when is it best to avoid it

Is it better to use inherited scope (i.e scope:true) when creating a directive, or is it more appropriate not to use it (i.e scope:false)? I grasp the distinction between scope types and their respective functionalities. However, I am uncertain about whic ...

Display sub-objects within Chart.js

I'm currently tackling a project in Ionic 3 where I am utilizing an API that returns a JSON response with nested objects. My goal is to display certain aspects of these objects within a bar graph using chart.js. Unfortunately, I lack experience in ma ...

Guide to automatically loading a default child route in Angular 1.5 using ui-router

Hello, I am looking to set a default child route to load as soon as the page loads. Below is the code snippet: $stateProvider.state('userlist', { url: '/users', component: 'users', data:{"name":"abhi"}, resolv ...

Retrieve information from a database by utilizing AJAX and store it in a JavaScript array

I'm facing an issue where I can retrieve data from the PHP file, but not from the database to my JavaScript code. I am using Ajax to fetch the data from the database, then passing it to the PHP file, and finally trying to filter this data using JavaSc ...

Issues with sending data using ajax

Trying to get weinre working through Ajax by calling this on dom ready: $.ajax({ url: 'http://debug.build.phonegap.com/target/target-script-min.js#hutber', dataType: "script", crossDomain: true, error: function(data){ c( ...

Is it possible to capture and generate an AxiosPromise inside a function?

I am looking to make a change in a function that currently returns an AxiosPromise. Here is the existing code: example(){ return api.get(url); } The api.get call returns an object of type AxiosPromise<any>. I would like to modify this function so ...

Express and Webpack Error: "SyntaxError: Unexpected token <"

I am facing difficulties while testing my React webpage that I built using Webpack. When trying to run an Express server, the localhost page appears blank with a console message saying Uncaught SyntaxError: Unexpected token <. It seems like the webpage ...

Should Angular libraries be developed using Typescript or transpiled into JavaScript?

Currently, I am in the process of developing a library that will be available as an Angular module through npm. The library itself has been written using typescript. Everything was functioning perfectly up until Angular version 5.0.0, but after this update ...

Displaying the age figure in JSX code with a red and bold formatting

I have a webpage with a button labeled "Increase Age". Every time this button is clicked, the person's age increases. How can I ensure that once the age surpasses 10, it is displayed in bold text on a red background? This should be implemented below t ...

How to retrieve data attribute from a different attribute in VueJS

I'm working with code that utilizes the VueGoodTable component, and I'm looking for a way to allow users to dynamically change the unit of the amount displayed: <template> <div class="container"> <h1>Welcome to t ...

Connect various models together, or create synchronized computed properties

At times, the model abstraction may fall short, leading to the necessity of synchronizing two different models. For instance, I have two lists linked by an angular sortable, which requires a model structure like this: left = [{name:"one"}, {name:"two"}]; ...

I have an Observable but I need to convert it into a String

Seeking assistance with Angular translation service and Kendo.UI components. In the Kendo.UI documentation, it mentions the use of MessageService for component translation implementation. To achieve this, an abstract class must be extended containing a m ...

Modify the value of mat-slide-toggle from TypeScript code

This is the HTML code I have for a mat-slide-toggle element, with a toggleStatus() function: <span class="form-control form-control-plaintext"> <mat-slide-toggle name="status" checked="" ...

Switching the class or modifying the style of an element when it is clicked in Vue.js

The process of retrieving data can be quite intricate. I have an array called "tweets" where the data is stored, and each tweet is represented as a card. I am able to successfully change the style of a card when it's clicked using the markTweet functi ...

What is the best way to eliminate a vertical line from the canvas in react-chartjs-2?

Can someone please lend me a hand? I've been working on a project in React JS that involves using react-chartjs-2 to display charts. I'm trying to incorporate a range slider for the chart to manipulate values on the x-axis, as well as two vertic ...

Make sure that every component in create-react-app includes an import for react so that it can be properly

Currently, I am working on a TypeScript project based on create-react-app which serves as the foundation for a React component that I plan to release as a standalone package. However, when using this package externally, I need to ensure that import React ...

The attribute 'elements' is not present within the data type 'Chart'

var canvas = document.getElementById("canvas"); var tooltipCanvas = document.getElementById("tooltip-canvas"); var gradientBlue = canvas.getContext('2d').createLinearGradient(0, 0, 0, 150); gradientBlue.addColorStop(0, '#5555FF'); grad ...

Having trouble transferring data from JavaScript to PHP via POST method

Hi there, this is my first time posting and I could really use some assistance. I have a bit of a roadblock with two Symfony forms on a page that don't seem to be working properly. The first form is for a contract, while the second one is used to pop ...

show information retrieved from database according to the drop-down menu selection

Can anyone assist me with this query? I have a drop-down menu that includes "Shop A" and "Shop B". Shop A has a value of 1, and Shop B has a value of 2. When I select Shop A from the dropdown, I want to display the data from the database as a table specifi ...