VueJS - Accessing store data inside mounted

Viewed 20977

I'm having trouble understanding the following:

I have a store which contains variables needed for the application. In particular, there is a globalCompanies which stores:

globalCompanies: {
   current: [],
   all: [],
   currentName: "",
}

Inside another component, I want to do the following:

mounted() {
   this.$store.dispatch( "fetchUsers" );

   var currentName = this.$store.state.globalCompanies.currentName; 

   console.log(currentName); 
},

However, this just shows as empty. I know the value is there because I have computed which returns the currentName and it works fine inside the view itself. It just doesn't like the fact that it's in the mounted component.

Where am I going wrong and what can I do to resolve this issue? I really need to capture the companies Name in order to use it for some real time events.

2 Answers

VueJS - Accessing Store Data Inside Mounted

Ran into this issue and it turned out to be a scope issue.

Store:

export default () => {
     items:[],
     globalCompanies:{
        current:[],
        all:[],
        currentName: "Something"
     },
     ok: "Here you go"
}

Getters:

export default {
   getGlobalCompanies(state){
      return state.globalCompanies;
   }
}

Mounted: This works...

mounted() {
   // Initialize inside mounted to ensure store is within scope
   const { getters } = this.$store; 

   const thisWorks = () => {
      const globalCompanies = getters.getGlobalCompanies;
   }
},

This is Bad: Reaching for the store outside the mounted scope

mounted() {
   function ThisDontWork() {
      const { getters } = this.$store; // this.$store == undefined
   }

   ThisDontWork();
},
Related