0

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?

1
  • 1
    Where and when do you call console.log(id)? This is probably the real issue here (you may have it too early, when it's still undefined). To be sure, you could console.log it on a button @click. Commented Apr 25, 2022 at 2:42

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

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.