Categories
Vue Answers

How to use a Vuex store in an Axios interceptor with Vue.js?

Spread the love

Sometimes, we want to use a Vuex store in an Axios interceptor with Vue.js.

In this article, we’ll look at how to use a Vuex store in an Axios interceptor with Vue.js.

How to use a Vuex store in an Axios interceptor with Vue.js?

To use a Vuex store in an Axios interceptor with Vue.js, we can import the store and use it directly.

For instance, we write

import axios from "axios";
import store from "your/store/path/store";

axios.interceptors.request.use(
  (config) => {
    const token = store.getters.token;
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (err) => {
    return Promise.reject(err);
  }
);

to import the Vuex store instance with

import store from "your/store/path/store";

Then we get the token getter value with store.getters.token.

Conclusion

To use a Vuex store in an Axios interceptor with Vue.js, we can import the store and use it directly.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *