I'm trying to use mapState in my Vue component written in TypeScript.
As suggested here: How to use mapState function in typescript syntax when using vuex?
I did this to make it happen:
<template>
<SomeComponent
:title="title">
</SomeComponent>
</template>
<script lang="ts">
import Vue from 'vue'
...
const MyComponentProps = Vue.extend({ })
@Component({
components: {
SomeComponent,
...
},
...mapGetters(['currentSubscription']),
...mapState({
content: (state: RootState) => state.content,
})
})
export default class MyComponent extends MyComponentProps {
content!: ContentModel
get title () {
this.content.someTitle
}
</script>
The problem is that I get this error:
"TypeError: Cannot read property of undefined (read 'someTitle')"
When I get the state property directly from the store (without using mapState), I don't get any errors:
get title () {
this.$store.state.content.someTitle
}
Also when I use the watch I can do this:
title!: ''
...
@Watch('content')
onPropertyChanged (value: ContentModel) {
this.title = value.someTitle
}
But I find this solution verbose and less readable, and in my opinion it misses the whole mapState idea.
My question is why I don't get an error when calling the store directly, is there a way for me to use mapState with a computed property?
I found the problem, I didn't nest the map inside the
calculation.@Component({ components: { SomeComponent, ... }, computed { // <--- This line solved it ...mapGetters(['currentSubscription']), ...mapState({ content: (state: RootState) => state.content, }) } })This way everything will be normal