Dave Merwin
Dave Merwin

Reputation: 1412

Trying to access a state object in mounted() in my Vue component

I have a Vuex state that holds a user ID. In my component's mounted(), I try to use that user ID, but it's always null.

How do I get the state from my computed mapGetters into my mounted()?

Here's my computed:

computed: {
  ...mapGetters('auth', [
    'userid'
  ])
}

And here's my mounted():

mounted () {
  HTTP.get('account/' + this.userid + '/')
      .then((response) => {
        this.account = response.data
      })
}

The this.userid is always null.

BTW when I look at the Vue inspector, the auth/userid has the correct value in the getter auth/userid. How do I access auth.userid from mounted()?

Upvotes: 3

Views: 4782

Answers (2)

ittus
ittus

Reputation: 22393

userid might not be available at the time component is mounted. You can fix it by watching userid value, and only call HTTP request when userid is changed and available:

computed: {
  ...mapGetters('auth', [
    'userid'
  ])
},
watch: {
  'userid': {
    handler (newVal) {
      if (newVal) { // check if userid is available
        this.getAccountInformation()
      }
    },
    immediate: true // make this watch function is called when component created
  }
},
methods: {
  getAccountInformation () {
    HTTP.get('account/' + this.userid + '/')
        .then((response) => {
          this.account = response.data
        })
  }
}

Upvotes: 8

Steven Spungin
Steven Spungin

Reputation: 29071

DEBUG

To debug this, first skip the mapGetters, and even getters, and return your state directly.

For example.

computed:{
   userId() { return this.$store.state.auth.userid }
}

I don't know how your store or modules are set up, so you might have to change things a bit.

Once that works, add it to your getters and use this.$store.getters.userid, or such.

Finally, when that works, try your original mapGetters and double check your module alias.

POSSIBLE ASYNC ISSUE

Now, on the other hand, if your getter is async, you will also get a null, before the userid promise resolves. You would have to use an asyncComputed, or wait for the result in your mounted.

Upvotes: 0

Related Questions