'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:
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?
Solution 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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Gustavo IAS |

