0

I am trying to use my store state in main.js but it vanishes my component, can I use state in mian.js

Axios.defaults.headers.common['BranchId'] = this.$store.state.myBrachId,

if not what how can I set the default headers dynamically then..?

3 Answers 3

2

You're asking how to access a Vuex store outside a Vue component. The syntax that you're currently using is only valid if you're writing a Vue component.

In case you want to access Vuex outside (any .js file) you should, first, export the store. Then, import that store in your file and finally use the store as you place.

Let's see an example:

store/index.js

export const store = new Vuex.Store({
 state () {
  myBrachId: 'niceBranch007'
 }
});

Then, in any other .js file (main.js in your case)

import { store } from 'store/index.js'
console.log(store.state.myBrachId)
Sign up to request clarification or add additional context in comments.

Comments

1

If you're trying to add headers to axios I'd ask you to consider if you should really be getting that header data from a Vuex store anyways. Remember that any browser refresh will clear your store so you should not rely on it's availability more than you need to. Using localStorage or sessionStorage might be better for what you're looking to do here.

Comments

0

I am doing this right now this is my store

import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

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

    branchId: "",
  },
  getters:{
  
  },
  mutations: {
    
  },
  actions: {},
  modules: {}
});

In header cmponent

this.$store.state.branchId = this.Branches[index].branchId;

in main js

import Axios from 'axios'
import { store } from './store/index'
Axios.defaults.headers.common['BranchId'] = store.state.branchId;

this is not setting axios header, it comes empty

1 Comment

Instead of pasting all of your code, you should only paste the part of the code that the asker of the questions needs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.