rc07jnr
rc07jnr

Reputation: 59

How can I use Vuex state array values in a vue component?

I have a store.js file that have the following state and getter:

state: {
    isLoggedIn: false,
    user: {}
},

getters: {
    getUserId: state => state.user.id
},

After a user is logged in, the isLoggedIn becomes true and user is populated with the user's info as seen in image below:

enter image description here

As you can see I have a getter, in the store.js that retrieves the correct ID but when I go to use this in my component, it comes up as undefined.

My component looks like this:

const id = this.$store.getters.getUserId;
console.log(id);

How can I use the value of getUserId in my component?

Upvotes: 0

Views: 641

Answers (1)

Gustavo IAS
Gustavo IAS

Reputation: 198

I limit myself only to solving the problem based on the interpretation of the code provided

Solution 1:

const id = this.$store.getters.getUserId; I agree with the comment (kissu), but well regardless of where: in a hook, a method... You can use mapGetters in a computed property. Import:

import {mapGetters} from 'vuex // add this line in your component

 <template>
...
 UserId: {{ getUserId }}
...
</template>

<script>
import {mapGetters} from 'vuex 
.
.
computed: {
   ...mapGetters(['getUserId']) // Also can use namespaces if preferred
}
...
</script>

Solution 2

You can used directly in DOM

<template>
...
 UserId: {{ $store.getters.getUserId }}
...
</template>

I hope it will be useful

Upvotes: 1

Related Questions