I am trying to use mapState
in my TypeScript
ed written Vue
component.
As advised here: How to use mapState function in typescript syntax when using vuex?
I am doing this in order to achieve it:
<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 issue is I am getting this error:
"TypeError: Cannot read properties of undefined (reading 'someTitle')"
When I am getting the state properties directly from the store (not with mapState) I am not receiving any errors:
get title () {
this.$store.state.content.someTitle
}
Also when I am using watch I am able to do it:
title!: ''
...
@Watch('content')
onPropertyChanged (value: ContentModel) {
this.title = value.someTitle
}
but I find this solution a verbose and less readable one, which in my opinion misses the whole mapState
idea.
My question is why when directly calling the store I am not getting errors and is there a way for me to use mapState
with computed properties?
I've found the problem, I did not nest the maps in computed
.
@Component({
components: {
SomeComponent,
...
},
computed { // <--- This line solved it
...mapGetters(['currentSubscription']),
...mapState({
content: (state: RootState) => state.content,
})
}
})
This way it is all working fine