[Vuejs]-Set axios authorization header depends on store changes

0👍

First of all, you should be careful with Vue’s reactivity caveats which affect Vuex aswell. In your case, you’re adding a new property inside an object in a mutation.

Back to the main issue, your axios.js file is being executed before the Store instance is built, that’s why you cannot access to it and you get undefined.

What I’d do is:

axios.js

import axios from 'axios';
const API_URL = process.env.API_URL;

export default (store) => axios.create({
  baseURL: API_URL,
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${store.getters.auth.token}`
  }
});

and then in your main file, where you have the main Vue instantiation I’d just run the function there, exporting the return of that function.

Leave a comment